util.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  1. #
  2. # Copyright (C) 2012-2021 The Python Software Foundation.
  3. # See LICENSE.txt and CONTRIBUTORS.txt.
  4. #
  5. import codecs
  6. from collections import deque
  7. import contextlib
  8. import csv
  9. from glob import iglob as std_iglob
  10. import io
  11. import json
  12. import logging
  13. import os
  14. import py_compile
  15. import re
  16. import socket
  17. try:
  18. import ssl
  19. except ImportError: # pragma: no cover
  20. ssl = None
  21. import subprocess
  22. import sys
  23. import tarfile
  24. import tempfile
  25. import textwrap
  26. try:
  27. import threading
  28. except ImportError: # pragma: no cover
  29. import dummy_threading as threading
  30. import time
  31. from . import DistlibException
  32. from .compat import (string_types, text_type, shutil, raw_input, StringIO,
  33. cache_from_source, urlopen, urljoin, httplib, xmlrpclib,
  34. splittype, HTTPHandler, BaseConfigurator, valid_ident,
  35. Container, configparser, URLError, ZipFile, fsdecode,
  36. unquote, urlparse)
  37. logger = logging.getLogger(__name__)
  38. #
  39. # Requirement parsing code as per PEP 508
  40. #
  41. IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')
  42. VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')
  43. COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')
  44. MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')
  45. OR = re.compile(r'^or\b\s*')
  46. AND = re.compile(r'^and\b\s*')
  47. NON_SPACE = re.compile(r'(\S+)\s*')
  48. STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')
  49. def parse_marker(marker_string):
  50. """
  51. Parse a marker string and return a dictionary containing a marker expression.
  52. The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
  53. the expression grammar, or strings. A string contained in quotes is to be
  54. interpreted as a literal string, and a string not contained in quotes is a
  55. variable (such as os_name).
  56. """
  57. def marker_var(remaining):
  58. # either identifier, or literal string
  59. m = IDENTIFIER.match(remaining)
  60. if m:
  61. result = m.groups()[0]
  62. remaining = remaining[m.end():]
  63. elif not remaining:
  64. raise SyntaxError('unexpected end of input')
  65. else:
  66. q = remaining[0]
  67. if q not in '\'"':
  68. raise SyntaxError('invalid expression: %s' % remaining)
  69. oq = '\'"'.replace(q, '')
  70. remaining = remaining[1:]
  71. parts = [q]
  72. while remaining:
  73. # either a string chunk, or oq, or q to terminate
  74. if remaining[0] == q:
  75. break
  76. elif remaining[0] == oq:
  77. parts.append(oq)
  78. remaining = remaining[1:]
  79. else:
  80. m = STRING_CHUNK.match(remaining)
  81. if not m:
  82. raise SyntaxError('error in string literal: %s' % remaining)
  83. parts.append(m.groups()[0])
  84. remaining = remaining[m.end():]
  85. else:
  86. s = ''.join(parts)
  87. raise SyntaxError('unterminated string: %s' % s)
  88. parts.append(q)
  89. result = ''.join(parts)
  90. remaining = remaining[1:].lstrip() # skip past closing quote
  91. return result, remaining
  92. def marker_expr(remaining):
  93. if remaining and remaining[0] == '(':
  94. result, remaining = marker(remaining[1:].lstrip())
  95. if remaining[0] != ')':
  96. raise SyntaxError('unterminated parenthesis: %s' % remaining)
  97. remaining = remaining[1:].lstrip()
  98. else:
  99. lhs, remaining = marker_var(remaining)
  100. while remaining:
  101. m = MARKER_OP.match(remaining)
  102. if not m:
  103. break
  104. op = m.groups()[0]
  105. remaining = remaining[m.end():]
  106. rhs, remaining = marker_var(remaining)
  107. lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
  108. result = lhs
  109. return result, remaining
  110. def marker_and(remaining):
  111. lhs, remaining = marker_expr(remaining)
  112. while remaining:
  113. m = AND.match(remaining)
  114. if not m:
  115. break
  116. remaining = remaining[m.end():]
  117. rhs, remaining = marker_expr(remaining)
  118. lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
  119. return lhs, remaining
  120. def marker(remaining):
  121. lhs, remaining = marker_and(remaining)
  122. while remaining:
  123. m = OR.match(remaining)
  124. if not m:
  125. break
  126. remaining = remaining[m.end():]
  127. rhs, remaining = marker_and(remaining)
  128. lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
  129. return lhs, remaining
  130. return marker(marker_string)
  131. def parse_requirement(req):
  132. """
  133. Parse a requirement passed in as a string. Return a Container
  134. whose attributes contain the various parts of the requirement.
  135. """
  136. remaining = req.strip()
  137. if not remaining or remaining.startswith('#'):
  138. return None
  139. m = IDENTIFIER.match(remaining)
  140. if not m:
  141. raise SyntaxError('name expected: %s' % remaining)
  142. distname = m.groups()[0]
  143. remaining = remaining[m.end():]
  144. extras = mark_expr = versions = uri = None
  145. if remaining and remaining[0] == '[':
  146. i = remaining.find(']', 1)
  147. if i < 0:
  148. raise SyntaxError('unterminated extra: %s' % remaining)
  149. s = remaining[1:i]
  150. remaining = remaining[i + 1:].lstrip()
  151. extras = []
  152. while s:
  153. m = IDENTIFIER.match(s)
  154. if not m:
  155. raise SyntaxError('malformed extra: %s' % s)
  156. extras.append(m.groups()[0])
  157. s = s[m.end():]
  158. if not s:
  159. break
  160. if s[0] != ',':
  161. raise SyntaxError('comma expected in extras: %s' % s)
  162. s = s[1:].lstrip()
  163. if not extras:
  164. extras = None
  165. if remaining:
  166. if remaining[0] == '@':
  167. # it's a URI
  168. remaining = remaining[1:].lstrip()
  169. m = NON_SPACE.match(remaining)
  170. if not m:
  171. raise SyntaxError('invalid URI: %s' % remaining)
  172. uri = m.groups()[0]
  173. t = urlparse(uri)
  174. # there are issues with Python and URL parsing, so this test
  175. # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
  176. # always parse invalid URLs correctly - it should raise
  177. # exceptions for malformed URLs
  178. if not (t.scheme and t.netloc):
  179. raise SyntaxError('Invalid URL: %s' % uri)
  180. remaining = remaining[m.end():].lstrip()
  181. else:
  182. def get_versions(ver_remaining):
  183. """
  184. Return a list of operator, version tuples if any are
  185. specified, else None.
  186. """
  187. m = COMPARE_OP.match(ver_remaining)
  188. versions = None
  189. if m:
  190. versions = []
  191. while True:
  192. op = m.groups()[0]
  193. ver_remaining = ver_remaining[m.end():]
  194. m = VERSION_IDENTIFIER.match(ver_remaining)
  195. if not m:
  196. raise SyntaxError('invalid version: %s' % ver_remaining)
  197. v = m.groups()[0]
  198. versions.append((op, v))
  199. ver_remaining = ver_remaining[m.end():]
  200. if not ver_remaining or ver_remaining[0] != ',':
  201. break
  202. ver_remaining = ver_remaining[1:].lstrip()
  203. # Some packages have a trailing comma which would break things
  204. # See issue #148
  205. if not ver_remaining:
  206. break
  207. m = COMPARE_OP.match(ver_remaining)
  208. if not m:
  209. raise SyntaxError('invalid constraint: %s' % ver_remaining)
  210. if not versions:
  211. versions = None
  212. return versions, ver_remaining
  213. if remaining[0] != '(':
  214. versions, remaining = get_versions(remaining)
  215. else:
  216. i = remaining.find(')', 1)
  217. if i < 0:
  218. raise SyntaxError('unterminated parenthesis: %s' % remaining)
  219. s = remaining[1:i]
  220. remaining = remaining[i + 1:].lstrip()
  221. # As a special diversion from PEP 508, allow a version number
  222. # a.b.c in parentheses as a synonym for ~= a.b.c (because this
  223. # is allowed in earlier PEPs)
  224. if COMPARE_OP.match(s):
  225. versions, _ = get_versions(s)
  226. else:
  227. m = VERSION_IDENTIFIER.match(s)
  228. if not m:
  229. raise SyntaxError('invalid constraint: %s' % s)
  230. v = m.groups()[0]
  231. s = s[m.end():].lstrip()
  232. if s:
  233. raise SyntaxError('invalid constraint: %s' % s)
  234. versions = [('~=', v)]
  235. if remaining:
  236. if remaining[0] != ';':
  237. raise SyntaxError('invalid requirement: %s' % remaining)
  238. remaining = remaining[1:].lstrip()
  239. mark_expr, remaining = parse_marker(remaining)
  240. if remaining and remaining[0] != '#':
  241. raise SyntaxError('unexpected trailing data: %s' % remaining)
  242. if not versions:
  243. rs = distname
  244. else:
  245. rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
  246. return Container(name=distname, extras=extras, constraints=versions,
  247. marker=mark_expr, url=uri, requirement=rs)
  248. def get_resources_dests(resources_root, rules):
  249. """Find destinations for resources files"""
  250. def get_rel_path(root, path):
  251. # normalizes and returns a lstripped-/-separated path
  252. root = root.replace(os.path.sep, '/')
  253. path = path.replace(os.path.sep, '/')
  254. assert path.startswith(root)
  255. return path[len(root):].lstrip('/')
  256. destinations = {}
  257. for base, suffix, dest in rules:
  258. prefix = os.path.join(resources_root, base)
  259. for abs_base in iglob(prefix):
  260. abs_glob = os.path.join(abs_base, suffix)
  261. for abs_path in iglob(abs_glob):
  262. resource_file = get_rel_path(resources_root, abs_path)
  263. if dest is None: # remove the entry if it was here
  264. destinations.pop(resource_file, None)
  265. else:
  266. rel_path = get_rel_path(abs_base, abs_path)
  267. rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
  268. destinations[resource_file] = rel_dest + '/' + rel_path
  269. return destinations
  270. def in_venv():
  271. if hasattr(sys, 'real_prefix'):
  272. # virtualenv venvs
  273. result = True
  274. else:
  275. # PEP 405 venvs
  276. result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
  277. return result
  278. def get_executable():
  279. # The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as
  280. # changes to the stub launcher mean that sys.executable always points
  281. # to the stub on OS X
  282. # if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
  283. # in os.environ):
  284. # result = os.environ['__PYVENV_LAUNCHER__']
  285. # else:
  286. # result = sys.executable
  287. # return result
  288. # Avoid normcasing: see issue #143
  289. # result = os.path.normcase(sys.executable)
  290. result = sys.executable
  291. if not isinstance(result, text_type):
  292. result = fsdecode(result)
  293. return result
  294. def proceed(prompt, allowed_chars, error_prompt=None, default=None):
  295. p = prompt
  296. while True:
  297. s = raw_input(p)
  298. p = prompt
  299. if not s and default:
  300. s = default
  301. if s:
  302. c = s[0].lower()
  303. if c in allowed_chars:
  304. break
  305. if error_prompt:
  306. p = '%c: %s\n%s' % (c, error_prompt, prompt)
  307. return c
  308. def extract_by_key(d, keys):
  309. if isinstance(keys, string_types):
  310. keys = keys.split()
  311. result = {}
  312. for key in keys:
  313. if key in d:
  314. result[key] = d[key]
  315. return result
  316. def read_exports(stream):
  317. if sys.version_info[0] >= 3:
  318. # needs to be a text stream
  319. stream = codecs.getreader('utf-8')(stream)
  320. # Try to load as JSON, falling back on legacy format
  321. data = stream.read()
  322. stream = StringIO(data)
  323. try:
  324. jdata = json.load(stream)
  325. result = jdata['extensions']['python.exports']['exports']
  326. for group, entries in result.items():
  327. for k, v in entries.items():
  328. s = '%s = %s' % (k, v)
  329. entry = get_export_entry(s)
  330. assert entry is not None
  331. entries[k] = entry
  332. return result
  333. except Exception:
  334. stream.seek(0, 0)
  335. def read_stream(cp, stream):
  336. if hasattr(cp, 'read_file'):
  337. cp.read_file(stream)
  338. else:
  339. cp.readfp(stream)
  340. cp = configparser.ConfigParser()
  341. try:
  342. read_stream(cp, stream)
  343. except configparser.MissingSectionHeaderError:
  344. stream.close()
  345. data = textwrap.dedent(data)
  346. stream = StringIO(data)
  347. read_stream(cp, stream)
  348. result = {}
  349. for key in cp.sections():
  350. result[key] = entries = {}
  351. for name, value in cp.items(key):
  352. s = '%s = %s' % (name, value)
  353. entry = get_export_entry(s)
  354. assert entry is not None
  355. #entry.dist = self
  356. entries[name] = entry
  357. return result
  358. def write_exports(exports, stream):
  359. if sys.version_info[0] >= 3:
  360. # needs to be a text stream
  361. stream = codecs.getwriter('utf-8')(stream)
  362. cp = configparser.ConfigParser()
  363. for k, v in exports.items():
  364. # TODO check k, v for valid values
  365. cp.add_section(k)
  366. for entry in v.values():
  367. if entry.suffix is None:
  368. s = entry.prefix
  369. else:
  370. s = '%s:%s' % (entry.prefix, entry.suffix)
  371. if entry.flags:
  372. s = '%s [%s]' % (s, ', '.join(entry.flags))
  373. cp.set(k, entry.name, s)
  374. cp.write(stream)
  375. @contextlib.contextmanager
  376. def tempdir():
  377. td = tempfile.mkdtemp()
  378. try:
  379. yield td
  380. finally:
  381. shutil.rmtree(td)
  382. @contextlib.contextmanager
  383. def chdir(d):
  384. cwd = os.getcwd()
  385. try:
  386. os.chdir(d)
  387. yield
  388. finally:
  389. os.chdir(cwd)
  390. @contextlib.contextmanager
  391. def socket_timeout(seconds=15):
  392. cto = socket.getdefaulttimeout()
  393. try:
  394. socket.setdefaulttimeout(seconds)
  395. yield
  396. finally:
  397. socket.setdefaulttimeout(cto)
  398. class cached_property(object):
  399. def __init__(self, func):
  400. self.func = func
  401. #for attr in ('__name__', '__module__', '__doc__'):
  402. # setattr(self, attr, getattr(func, attr, None))
  403. def __get__(self, obj, cls=None):
  404. if obj is None:
  405. return self
  406. value = self.func(obj)
  407. object.__setattr__(obj, self.func.__name__, value)
  408. #obj.__dict__[self.func.__name__] = value = self.func(obj)
  409. return value
  410. def convert_path(pathname):
  411. """Return 'pathname' as a name that will work on the native filesystem.
  412. The path is split on '/' and put back together again using the current
  413. directory separator. Needed because filenames in the setup script are
  414. always supplied in Unix style, and have to be converted to the local
  415. convention before we can actually use them in the filesystem. Raises
  416. ValueError on non-Unix-ish systems if 'pathname' either starts or
  417. ends with a slash.
  418. """
  419. if os.sep == '/':
  420. return pathname
  421. if not pathname:
  422. return pathname
  423. if pathname[0] == '/':
  424. raise ValueError("path '%s' cannot be absolute" % pathname)
  425. if pathname[-1] == '/':
  426. raise ValueError("path '%s' cannot end with '/'" % pathname)
  427. paths = pathname.split('/')
  428. while os.curdir in paths:
  429. paths.remove(os.curdir)
  430. if not paths:
  431. return os.curdir
  432. return os.path.join(*paths)
  433. class FileOperator(object):
  434. def __init__(self, dry_run=False):
  435. self.dry_run = dry_run
  436. self.ensured = set()
  437. self._init_record()
  438. def _init_record(self):
  439. self.record = False
  440. self.files_written = set()
  441. self.dirs_created = set()
  442. def record_as_written(self, path):
  443. if self.record:
  444. self.files_written.add(path)
  445. def newer(self, source, target):
  446. """Tell if the target is newer than the source.
  447. Returns true if 'source' exists and is more recently modified than
  448. 'target', or if 'source' exists and 'target' doesn't.
  449. Returns false if both exist and 'target' is the same age or younger
  450. than 'source'. Raise PackagingFileError if 'source' does not exist.
  451. Note that this test is not very accurate: files created in the same
  452. second will have the same "age".
  453. """
  454. if not os.path.exists(source):
  455. raise DistlibException("file '%r' does not exist" %
  456. os.path.abspath(source))
  457. if not os.path.exists(target):
  458. return True
  459. return os.stat(source).st_mtime > os.stat(target).st_mtime
  460. def copy_file(self, infile, outfile, check=True):
  461. """Copy a file respecting dry-run and force flags.
  462. """
  463. self.ensure_dir(os.path.dirname(outfile))
  464. logger.info('Copying %s to %s', infile, outfile)
  465. if not self.dry_run:
  466. msg = None
  467. if check:
  468. if os.path.islink(outfile):
  469. msg = '%s is a symlink' % outfile
  470. elif os.path.exists(outfile) and not os.path.isfile(outfile):
  471. msg = '%s is a non-regular file' % outfile
  472. if msg:
  473. raise ValueError(msg + ' which would be overwritten')
  474. shutil.copyfile(infile, outfile)
  475. self.record_as_written(outfile)
  476. def copy_stream(self, instream, outfile, encoding=None):
  477. assert not os.path.isdir(outfile)
  478. self.ensure_dir(os.path.dirname(outfile))
  479. logger.info('Copying stream %s to %s', instream, outfile)
  480. if not self.dry_run:
  481. if encoding is None:
  482. outstream = open(outfile, 'wb')
  483. else:
  484. outstream = codecs.open(outfile, 'w', encoding=encoding)
  485. try:
  486. shutil.copyfileobj(instream, outstream)
  487. finally:
  488. outstream.close()
  489. self.record_as_written(outfile)
  490. def write_binary_file(self, path, data):
  491. self.ensure_dir(os.path.dirname(path))
  492. if not self.dry_run:
  493. if os.path.exists(path):
  494. os.remove(path)
  495. with open(path, 'wb') as f:
  496. f.write(data)
  497. self.record_as_written(path)
  498. def write_text_file(self, path, data, encoding):
  499. self.write_binary_file(path, data.encode(encoding))
  500. def set_mode(self, bits, mask, files):
  501. if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):
  502. # Set the executable bits (owner, group, and world) on
  503. # all the files specified.
  504. for f in files:
  505. if self.dry_run:
  506. logger.info("changing mode of %s", f)
  507. else:
  508. mode = (os.stat(f).st_mode | bits) & mask
  509. logger.info("changing mode of %s to %o", f, mode)
  510. os.chmod(f, mode)
  511. set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)
  512. def ensure_dir(self, path):
  513. path = os.path.abspath(path)
  514. if path not in self.ensured and not os.path.exists(path):
  515. self.ensured.add(path)
  516. d, f = os.path.split(path)
  517. self.ensure_dir(d)
  518. logger.info('Creating %s' % path)
  519. if not self.dry_run:
  520. os.mkdir(path)
  521. if self.record:
  522. self.dirs_created.add(path)
  523. def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False):
  524. dpath = cache_from_source(path, not optimize)
  525. logger.info('Byte-compiling %s to %s', path, dpath)
  526. if not self.dry_run:
  527. if force or self.newer(path, dpath):
  528. if not prefix:
  529. diagpath = None
  530. else:
  531. assert path.startswith(prefix)
  532. diagpath = path[len(prefix):]
  533. compile_kwargs = {}
  534. if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'):
  535. compile_kwargs['invalidation_mode'] = py_compile.PycInvalidationMode.CHECKED_HASH
  536. py_compile.compile(path, dpath, diagpath, True, **compile_kwargs) # raise error
  537. self.record_as_written(dpath)
  538. return dpath
  539. def ensure_removed(self, path):
  540. if os.path.exists(path):
  541. if os.path.isdir(path) and not os.path.islink(path):
  542. logger.debug('Removing directory tree at %s', path)
  543. if not self.dry_run:
  544. shutil.rmtree(path)
  545. if self.record:
  546. if path in self.dirs_created:
  547. self.dirs_created.remove(path)
  548. else:
  549. if os.path.islink(path):
  550. s = 'link'
  551. else:
  552. s = 'file'
  553. logger.debug('Removing %s %s', s, path)
  554. if not self.dry_run:
  555. os.remove(path)
  556. if self.record:
  557. if path in self.files_written:
  558. self.files_written.remove(path)
  559. def is_writable(self, path):
  560. result = False
  561. while not result:
  562. if os.path.exists(path):
  563. result = os.access(path, os.W_OK)
  564. break
  565. parent = os.path.dirname(path)
  566. if parent == path:
  567. break
  568. path = parent
  569. return result
  570. def commit(self):
  571. """
  572. Commit recorded changes, turn off recording, return
  573. changes.
  574. """
  575. assert self.record
  576. result = self.files_written, self.dirs_created
  577. self._init_record()
  578. return result
  579. def rollback(self):
  580. if not self.dry_run:
  581. for f in list(self.files_written):
  582. if os.path.exists(f):
  583. os.remove(f)
  584. # dirs should all be empty now, except perhaps for
  585. # __pycache__ subdirs
  586. # reverse so that subdirs appear before their parents
  587. dirs = sorted(self.dirs_created, reverse=True)
  588. for d in dirs:
  589. flist = os.listdir(d)
  590. if flist:
  591. assert flist == ['__pycache__']
  592. sd = os.path.join(d, flist[0])
  593. os.rmdir(sd)
  594. os.rmdir(d) # should fail if non-empty
  595. self._init_record()
  596. def resolve(module_name, dotted_path):
  597. if module_name in sys.modules:
  598. mod = sys.modules[module_name]
  599. else:
  600. mod = __import__(module_name)
  601. if dotted_path is None:
  602. result = mod
  603. else:
  604. parts = dotted_path.split('.')
  605. result = getattr(mod, parts.pop(0))
  606. for p in parts:
  607. result = getattr(result, p)
  608. return result
  609. class ExportEntry(object):
  610. def __init__(self, name, prefix, suffix, flags):
  611. self.name = name
  612. self.prefix = prefix
  613. self.suffix = suffix
  614. self.flags = flags
  615. @cached_property
  616. def value(self):
  617. return resolve(self.prefix, self.suffix)
  618. def __repr__(self): # pragma: no cover
  619. return '<ExportEntry %s = %s:%s %s>' % (self.name, self.prefix,
  620. self.suffix, self.flags)
  621. def __eq__(self, other):
  622. if not isinstance(other, ExportEntry):
  623. result = False
  624. else:
  625. result = (self.name == other.name and
  626. self.prefix == other.prefix and
  627. self.suffix == other.suffix and
  628. self.flags == other.flags)
  629. return result
  630. __hash__ = object.__hash__
  631. ENTRY_RE = re.compile(r'''(?P<name>(\w|[-.+])+)
  632. \s*=\s*(?P<callable>(\w+)([:\.]\w+)*)
  633. \s*(\[\s*(?P<flags>[\w-]+(=\w+)?(,\s*\w+(=\w+)?)*)\s*\])?
  634. ''', re.VERBOSE)
  635. def get_export_entry(specification):
  636. m = ENTRY_RE.search(specification)
  637. if not m:
  638. result = None
  639. if '[' in specification or ']' in specification:
  640. raise DistlibException("Invalid specification "
  641. "'%s'" % specification)
  642. else:
  643. d = m.groupdict()
  644. name = d['name']
  645. path = d['callable']
  646. colons = path.count(':')
  647. if colons == 0:
  648. prefix, suffix = path, None
  649. else:
  650. if colons != 1:
  651. raise DistlibException("Invalid specification "
  652. "'%s'" % specification)
  653. prefix, suffix = path.split(':')
  654. flags = d['flags']
  655. if flags is None:
  656. if '[' in specification or ']' in specification:
  657. raise DistlibException("Invalid specification "
  658. "'%s'" % specification)
  659. flags = []
  660. else:
  661. flags = [f.strip() for f in flags.split(',')]
  662. result = ExportEntry(name, prefix, suffix, flags)
  663. return result
  664. def get_cache_base(suffix=None):
  665. """
  666. Return the default base location for distlib caches. If the directory does
  667. not exist, it is created. Use the suffix provided for the base directory,
  668. and default to '.distlib' if it isn't provided.
  669. On Windows, if LOCALAPPDATA is defined in the environment, then it is
  670. assumed to be a directory, and will be the parent directory of the result.
  671. On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
  672. directory - using os.expanduser('~') - will be the parent directory of
  673. the result.
  674. The result is just the directory '.distlib' in the parent directory as
  675. determined above, or with the name specified with ``suffix``.
  676. """
  677. if suffix is None:
  678. suffix = '.distlib'
  679. if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
  680. result = os.path.expandvars('$localappdata')
  681. else:
  682. # Assume posix, or old Windows
  683. result = os.path.expanduser('~')
  684. # we use 'isdir' instead of 'exists', because we want to
  685. # fail if there's a file with that name
  686. if os.path.isdir(result):
  687. usable = os.access(result, os.W_OK)
  688. if not usable:
  689. logger.warning('Directory exists but is not writable: %s', result)
  690. else:
  691. try:
  692. os.makedirs(result)
  693. usable = True
  694. except OSError:
  695. logger.warning('Unable to create %s', result, exc_info=True)
  696. usable = False
  697. if not usable:
  698. result = tempfile.mkdtemp()
  699. logger.warning('Default location unusable, using %s', result)
  700. return os.path.join(result, suffix)
  701. def path_to_cache_dir(path):
  702. """
  703. Convert an absolute path to a directory name for use in a cache.
  704. The algorithm used is:
  705. #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
  706. #. Any occurrence of ``os.sep`` is replaced with ``'--'``.
  707. #. ``'.cache'`` is appended.
  708. """
  709. d, p = os.path.splitdrive(os.path.abspath(path))
  710. if d:
  711. d = d.replace(':', '---')
  712. p = p.replace(os.sep, '--')
  713. return d + p + '.cache'
  714. def ensure_slash(s):
  715. if not s.endswith('/'):
  716. return s + '/'
  717. return s
  718. def parse_credentials(netloc):
  719. username = password = None
  720. if '@' in netloc:
  721. prefix, netloc = netloc.rsplit('@', 1)
  722. if ':' not in prefix:
  723. username = prefix
  724. else:
  725. username, password = prefix.split(':', 1)
  726. if username:
  727. username = unquote(username)
  728. if password:
  729. password = unquote(password)
  730. return username, password, netloc
  731. def get_process_umask():
  732. result = os.umask(0o22)
  733. os.umask(result)
  734. return result
  735. def is_string_sequence(seq):
  736. result = True
  737. i = None
  738. for i, s in enumerate(seq):
  739. if not isinstance(s, string_types):
  740. result = False
  741. break
  742. assert i is not None
  743. return result
  744. PROJECT_NAME_AND_VERSION = re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'
  745. '([a-z0-9_.+-]+)', re.I)
  746. PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')
  747. def split_filename(filename, project_name=None):
  748. """
  749. Extract name, version, python version from a filename (no extension)
  750. Return name, version, pyver or None
  751. """
  752. result = None
  753. pyver = None
  754. filename = unquote(filename).replace(' ', '-')
  755. m = PYTHON_VERSION.search(filename)
  756. if m:
  757. pyver = m.group(1)
  758. filename = filename[:m.start()]
  759. if project_name and len(filename) > len(project_name) + 1:
  760. m = re.match(re.escape(project_name) + r'\b', filename)
  761. if m:
  762. n = m.end()
  763. result = filename[:n], filename[n + 1:], pyver
  764. if result is None:
  765. m = PROJECT_NAME_AND_VERSION.match(filename)
  766. if m:
  767. result = m.group(1), m.group(3), pyver
  768. return result
  769. # Allow spaces in name because of legacy dists like "Twisted Core"
  770. NAME_VERSION_RE = re.compile(r'(?P<name>[\w .-]+)\s*'
  771. r'\(\s*(?P<ver>[^\s)]+)\)$')
  772. def parse_name_and_version(p):
  773. """
  774. A utility method used to get name and version from a string.
  775. From e.g. a Provides-Dist value.
  776. :param p: A value in a form 'foo (1.0)'
  777. :return: The name and version as a tuple.
  778. """
  779. m = NAME_VERSION_RE.match(p)
  780. if not m:
  781. raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
  782. d = m.groupdict()
  783. return d['name'].strip().lower(), d['ver']
  784. def get_extras(requested, available):
  785. result = set()
  786. requested = set(requested or [])
  787. available = set(available or [])
  788. if '*' in requested:
  789. requested.remove('*')
  790. result |= available
  791. for r in requested:
  792. if r == '-':
  793. result.add(r)
  794. elif r.startswith('-'):
  795. unwanted = r[1:]
  796. if unwanted not in available:
  797. logger.warning('undeclared extra: %s' % unwanted)
  798. if unwanted in result:
  799. result.remove(unwanted)
  800. else:
  801. if r not in available:
  802. logger.warning('undeclared extra: %s' % r)
  803. result.add(r)
  804. return result
  805. #
  806. # Extended metadata functionality
  807. #
  808. def _get_external_data(url):
  809. result = {}
  810. try:
  811. # urlopen might fail if it runs into redirections,
  812. # because of Python issue #13696. Fixed in locators
  813. # using a custom redirect handler.
  814. resp = urlopen(url)
  815. headers = resp.info()
  816. ct = headers.get('Content-Type')
  817. if not ct.startswith('application/json'):
  818. logger.debug('Unexpected response for JSON request: %s', ct)
  819. else:
  820. reader = codecs.getreader('utf-8')(resp)
  821. #data = reader.read().decode('utf-8')
  822. #result = json.loads(data)
  823. result = json.load(reader)
  824. except Exception as e:
  825. logger.exception('Failed to get external data for %s: %s', url, e)
  826. return result
  827. _external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
  828. def get_project_data(name):
  829. url = '%s/%s/project.json' % (name[0].upper(), name)
  830. url = urljoin(_external_data_base_url, url)
  831. result = _get_external_data(url)
  832. return result
  833. def get_package_data(name, version):
  834. url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)
  835. url = urljoin(_external_data_base_url, url)
  836. return _get_external_data(url)
  837. class Cache(object):
  838. """
  839. A class implementing a cache for resources that need to live in the file system
  840. e.g. shared libraries. This class was moved from resources to here because it
  841. could be used by other modules, e.g. the wheel module.
  842. """
  843. def __init__(self, base):
  844. """
  845. Initialise an instance.
  846. :param base: The base directory where the cache should be located.
  847. """
  848. # we use 'isdir' instead of 'exists', because we want to
  849. # fail if there's a file with that name
  850. if not os.path.isdir(base): # pragma: no cover
  851. os.makedirs(base)
  852. if (os.stat(base).st_mode & 0o77) != 0:
  853. logger.warning('Directory \'%s\' is not private', base)
  854. self.base = os.path.abspath(os.path.normpath(base))
  855. def prefix_to_dir(self, prefix):
  856. """
  857. Converts a resource prefix to a directory name in the cache.
  858. """
  859. return path_to_cache_dir(prefix)
  860. def clear(self):
  861. """
  862. Clear the cache.
  863. """
  864. not_removed = []
  865. for fn in os.listdir(self.base):
  866. fn = os.path.join(self.base, fn)
  867. try:
  868. if os.path.islink(fn) or os.path.isfile(fn):
  869. os.remove(fn)
  870. elif os.path.isdir(fn):
  871. shutil.rmtree(fn)
  872. except Exception:
  873. not_removed.append(fn)
  874. return not_removed
  875. class EventMixin(object):
  876. """
  877. A very simple publish/subscribe system.
  878. """
  879. def __init__(self):
  880. self._subscribers = {}
  881. def add(self, event, subscriber, append=True):
  882. """
  883. Add a subscriber for an event.
  884. :param event: The name of an event.
  885. :param subscriber: The subscriber to be added (and called when the
  886. event is published).
  887. :param append: Whether to append or prepend the subscriber to an
  888. existing subscriber list for the event.
  889. """
  890. subs = self._subscribers
  891. if event not in subs:
  892. subs[event] = deque([subscriber])
  893. else:
  894. sq = subs[event]
  895. if append:
  896. sq.append(subscriber)
  897. else:
  898. sq.appendleft(subscriber)
  899. def remove(self, event, subscriber):
  900. """
  901. Remove a subscriber for an event.
  902. :param event: The name of an event.
  903. :param subscriber: The subscriber to be removed.
  904. """
  905. subs = self._subscribers
  906. if event not in subs:
  907. raise ValueError('No subscribers: %r' % event)
  908. subs[event].remove(subscriber)
  909. def get_subscribers(self, event):
  910. """
  911. Return an iterator for the subscribers for an event.
  912. :param event: The event to return subscribers for.
  913. """
  914. return iter(self._subscribers.get(event, ()))
  915. def publish(self, event, *args, **kwargs):
  916. """
  917. Publish a event and return a list of values returned by its
  918. subscribers.
  919. :param event: The event to publish.
  920. :param args: The positional arguments to pass to the event's
  921. subscribers.
  922. :param kwargs: The keyword arguments to pass to the event's
  923. subscribers.
  924. """
  925. result = []
  926. for subscriber in self.get_subscribers(event):
  927. try:
  928. value = subscriber(event, *args, **kwargs)
  929. except Exception:
  930. logger.exception('Exception during event publication')
  931. value = None
  932. result.append(value)
  933. logger.debug('publish %s: args = %s, kwargs = %s, result = %s',
  934. event, args, kwargs, result)
  935. return result
  936. #
  937. # Simple sequencing
  938. #
  939. class Sequencer(object):
  940. def __init__(self):
  941. self._preds = {}
  942. self._succs = {}
  943. self._nodes = set() # nodes with no preds/succs
  944. def add_node(self, node):
  945. self._nodes.add(node)
  946. def remove_node(self, node, edges=False):
  947. if node in self._nodes:
  948. self._nodes.remove(node)
  949. if edges:
  950. for p in set(self._preds.get(node, ())):
  951. self.remove(p, node)
  952. for s in set(self._succs.get(node, ())):
  953. self.remove(node, s)
  954. # Remove empties
  955. for k, v in list(self._preds.items()):
  956. if not v:
  957. del self._preds[k]
  958. for k, v in list(self._succs.items()):
  959. if not v:
  960. del self._succs[k]
  961. def add(self, pred, succ):
  962. assert pred != succ
  963. self._preds.setdefault(succ, set()).add(pred)
  964. self._succs.setdefault(pred, set()).add(succ)
  965. def remove(self, pred, succ):
  966. assert pred != succ
  967. try:
  968. preds = self._preds[succ]
  969. succs = self._succs[pred]
  970. except KeyError: # pragma: no cover
  971. raise ValueError('%r not a successor of anything' % succ)
  972. try:
  973. preds.remove(pred)
  974. succs.remove(succ)
  975. except KeyError: # pragma: no cover
  976. raise ValueError('%r not a successor of %r' % (succ, pred))
  977. def is_step(self, step):
  978. return (step in self._preds or step in self._succs or
  979. step in self._nodes)
  980. def get_steps(self, final):
  981. if not self.is_step(final):
  982. raise ValueError('Unknown: %r' % final)
  983. result = []
  984. todo = []
  985. seen = set()
  986. todo.append(final)
  987. while todo:
  988. step = todo.pop(0)
  989. if step in seen:
  990. # if a step was already seen,
  991. # move it to the end (so it will appear earlier
  992. # when reversed on return) ... but not for the
  993. # final step, as that would be confusing for
  994. # users
  995. if step != final:
  996. result.remove(step)
  997. result.append(step)
  998. else:
  999. seen.add(step)
  1000. result.append(step)
  1001. preds = self._preds.get(step, ())
  1002. todo.extend(preds)
  1003. return reversed(result)
  1004. @property
  1005. def strong_connections(self):
  1006. #http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  1007. index_counter = [0]
  1008. stack = []
  1009. lowlinks = {}
  1010. index = {}
  1011. result = []
  1012. graph = self._succs
  1013. def strongconnect(node):
  1014. # set the depth index for this node to the smallest unused index
  1015. index[node] = index_counter[0]
  1016. lowlinks[node] = index_counter[0]
  1017. index_counter[0] += 1
  1018. stack.append(node)
  1019. # Consider successors
  1020. try:
  1021. successors = graph[node]
  1022. except Exception:
  1023. successors = []
  1024. for successor in successors:
  1025. if successor not in lowlinks:
  1026. # Successor has not yet been visited
  1027. strongconnect(successor)
  1028. lowlinks[node] = min(lowlinks[node],lowlinks[successor])
  1029. elif successor in stack:
  1030. # the successor is in the stack and hence in the current
  1031. # strongly connected component (SCC)
  1032. lowlinks[node] = min(lowlinks[node],index[successor])
  1033. # If `node` is a root node, pop the stack and generate an SCC
  1034. if lowlinks[node] == index[node]:
  1035. connected_component = []
  1036. while True:
  1037. successor = stack.pop()
  1038. connected_component.append(successor)
  1039. if successor == node: break
  1040. component = tuple(connected_component)
  1041. # storing the result
  1042. result.append(component)
  1043. for node in graph:
  1044. if node not in lowlinks:
  1045. strongconnect(node)
  1046. return result
  1047. @property
  1048. def dot(self):
  1049. result = ['digraph G {']
  1050. for succ in self._preds:
  1051. preds = self._preds[succ]
  1052. for pred in preds:
  1053. result.append(' %s -> %s;' % (pred, succ))
  1054. for node in self._nodes:
  1055. result.append(' %s;' % node)
  1056. result.append('}')
  1057. return '\n'.join(result)
  1058. #
  1059. # Unarchiving functionality for zip, tar, tgz, tbz, whl
  1060. #
  1061. ARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip',
  1062. '.tgz', '.tbz', '.whl')
  1063. def unarchive(archive_filename, dest_dir, format=None, check=True):
  1064. def check_path(path):
  1065. if not isinstance(path, text_type):
  1066. path = path.decode('utf-8')
  1067. p = os.path.abspath(os.path.join(dest_dir, path))
  1068. if not p.startswith(dest_dir) or p[plen] != os.sep:
  1069. raise ValueError('path outside destination: %r' % p)
  1070. dest_dir = os.path.abspath(dest_dir)
  1071. plen = len(dest_dir)
  1072. archive = None
  1073. if format is None:
  1074. if archive_filename.endswith(('.zip', '.whl')):
  1075. format = 'zip'
  1076. elif archive_filename.endswith(('.tar.gz', '.tgz')):
  1077. format = 'tgz'
  1078. mode = 'r:gz'
  1079. elif archive_filename.endswith(('.tar.bz2', '.tbz')):
  1080. format = 'tbz'
  1081. mode = 'r:bz2'
  1082. elif archive_filename.endswith('.tar'):
  1083. format = 'tar'
  1084. mode = 'r'
  1085. else: # pragma: no cover
  1086. raise ValueError('Unknown format for %r' % archive_filename)
  1087. try:
  1088. if format == 'zip':
  1089. archive = ZipFile(archive_filename, 'r')
  1090. if check:
  1091. names = archive.namelist()
  1092. for name in names:
  1093. check_path(name)
  1094. else:
  1095. archive = tarfile.open(archive_filename, mode)
  1096. if check:
  1097. names = archive.getnames()
  1098. for name in names:
  1099. check_path(name)
  1100. if format != 'zip' and sys.version_info[0] < 3:
  1101. # See Python issue 17153. If the dest path contains Unicode,
  1102. # tarfile extraction fails on Python 2.x if a member path name
  1103. # contains non-ASCII characters - it leads to an implicit
  1104. # bytes -> unicode conversion using ASCII to decode.
  1105. for tarinfo in archive.getmembers():
  1106. if not isinstance(tarinfo.name, text_type):
  1107. tarinfo.name = tarinfo.name.decode('utf-8')
  1108. archive.extractall(dest_dir)
  1109. finally:
  1110. if archive:
  1111. archive.close()
  1112. def zip_dir(directory):
  1113. """zip a directory tree into a BytesIO object"""
  1114. result = io.BytesIO()
  1115. dlen = len(directory)
  1116. with ZipFile(result, "w") as zf:
  1117. for root, dirs, files in os.walk(directory):
  1118. for name in files:
  1119. full = os.path.join(root, name)
  1120. rel = root[dlen:]
  1121. dest = os.path.join(rel, name)
  1122. zf.write(full, dest)
  1123. return result
  1124. #
  1125. # Simple progress bar
  1126. #
  1127. UNITS = ('', 'K', 'M', 'G','T','P')
  1128. class Progress(object):
  1129. unknown = 'UNKNOWN'
  1130. def __init__(self, minval=0, maxval=100):
  1131. assert maxval is None or maxval >= minval
  1132. self.min = self.cur = minval
  1133. self.max = maxval
  1134. self.started = None
  1135. self.elapsed = 0
  1136. self.done = False
  1137. def update(self, curval):
  1138. assert self.min <= curval
  1139. assert self.max is None or curval <= self.max
  1140. self.cur = curval
  1141. now = time.time()
  1142. if self.started is None:
  1143. self.started = now
  1144. else:
  1145. self.elapsed = now - self.started
  1146. def increment(self, incr):
  1147. assert incr >= 0
  1148. self.update(self.cur + incr)
  1149. def start(self):
  1150. self.update(self.min)
  1151. return self
  1152. def stop(self):
  1153. if self.max is not None:
  1154. self.update(self.max)
  1155. self.done = True
  1156. @property
  1157. def maximum(self):
  1158. return self.unknown if self.max is None else self.max
  1159. @property
  1160. def percentage(self):
  1161. if self.done:
  1162. result = '100 %'
  1163. elif self.max is None:
  1164. result = ' ?? %'
  1165. else:
  1166. v = 100.0 * (self.cur - self.min) / (self.max - self.min)
  1167. result = '%3d %%' % v
  1168. return result
  1169. def format_duration(self, duration):
  1170. if (duration <= 0) and self.max is None or self.cur == self.min:
  1171. result = '??:??:??'
  1172. #elif duration < 1:
  1173. # result = '--:--:--'
  1174. else:
  1175. result = time.strftime('%H:%M:%S', time.gmtime(duration))
  1176. return result
  1177. @property
  1178. def ETA(self):
  1179. if self.done:
  1180. prefix = 'Done'
  1181. t = self.elapsed
  1182. #import pdb; pdb.set_trace()
  1183. else:
  1184. prefix = 'ETA '
  1185. if self.max is None:
  1186. t = -1
  1187. elif self.elapsed == 0 or (self.cur == self.min):
  1188. t = 0
  1189. else:
  1190. #import pdb; pdb.set_trace()
  1191. t = float(self.max - self.min)
  1192. t /= self.cur - self.min
  1193. t = (t - 1) * self.elapsed
  1194. return '%s: %s' % (prefix, self.format_duration(t))
  1195. @property
  1196. def speed(self):
  1197. if self.elapsed == 0:
  1198. result = 0.0
  1199. else:
  1200. result = (self.cur - self.min) / self.elapsed
  1201. for unit in UNITS:
  1202. if result < 1000:
  1203. break
  1204. result /= 1000.0
  1205. return '%d %sB/s' % (result, unit)
  1206. #
  1207. # Glob functionality
  1208. #
  1209. RICH_GLOB = re.compile(r'\{([^}]*)\}')
  1210. _CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
  1211. _CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
  1212. def iglob(path_glob):
  1213. """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
  1214. if _CHECK_RECURSIVE_GLOB.search(path_glob):
  1215. msg = """invalid glob %r: recursive glob "**" must be used alone"""
  1216. raise ValueError(msg % path_glob)
  1217. if _CHECK_MISMATCH_SET.search(path_glob):
  1218. msg = """invalid glob %r: mismatching set marker '{' or '}'"""
  1219. raise ValueError(msg % path_glob)
  1220. return _iglob(path_glob)
  1221. def _iglob(path_glob):
  1222. rich_path_glob = RICH_GLOB.split(path_glob, 1)
  1223. if len(rich_path_glob) > 1:
  1224. assert len(rich_path_glob) == 3, rich_path_glob
  1225. prefix, set, suffix = rich_path_glob
  1226. for item in set.split(','):
  1227. for path in _iglob(''.join((prefix, item, suffix))):
  1228. yield path
  1229. else:
  1230. if '**' not in path_glob:
  1231. for item in std_iglob(path_glob):
  1232. yield item
  1233. else:
  1234. prefix, radical = path_glob.split('**', 1)
  1235. if prefix == '':
  1236. prefix = '.'
  1237. if radical == '':
  1238. radical = '*'
  1239. else:
  1240. # we support both
  1241. radical = radical.lstrip('/')
  1242. radical = radical.lstrip('\\')
  1243. for path, dir, files in os.walk(prefix):
  1244. path = os.path.normpath(path)
  1245. for fn in _iglob(os.path.join(path, radical)):
  1246. yield fn
  1247. if ssl:
  1248. from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname,
  1249. CertificateError)
  1250. #
  1251. # HTTPSConnection which verifies certificates/matches domains
  1252. #
  1253. class HTTPSConnection(httplib.HTTPSConnection):
  1254. ca_certs = None # set this to the path to the certs file (.pem)
  1255. check_domain = True # only used if ca_certs is not None
  1256. # noinspection PyPropertyAccess
  1257. def connect(self):
  1258. sock = socket.create_connection((self.host, self.port), self.timeout)
  1259. if getattr(self, '_tunnel_host', False):
  1260. self.sock = sock
  1261. self._tunnel()
  1262. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  1263. if hasattr(ssl, 'OP_NO_SSLv2'):
  1264. context.options |= ssl.OP_NO_SSLv2
  1265. if self.cert_file:
  1266. context.load_cert_chain(self.cert_file, self.key_file)
  1267. kwargs = {}
  1268. if self.ca_certs:
  1269. context.verify_mode = ssl.CERT_REQUIRED
  1270. context.load_verify_locations(cafile=self.ca_certs)
  1271. if getattr(ssl, 'HAS_SNI', False):
  1272. kwargs['server_hostname'] = self.host
  1273. self.sock = context.wrap_socket(sock, **kwargs)
  1274. if self.ca_certs and self.check_domain:
  1275. try:
  1276. match_hostname(self.sock.getpeercert(), self.host)
  1277. logger.debug('Host verified: %s', self.host)
  1278. except CertificateError: # pragma: no cover
  1279. self.sock.shutdown(socket.SHUT_RDWR)
  1280. self.sock.close()
  1281. raise
  1282. class HTTPSHandler(BaseHTTPSHandler):
  1283. def __init__(self, ca_certs, check_domain=True):
  1284. BaseHTTPSHandler.__init__(self)
  1285. self.ca_certs = ca_certs
  1286. self.check_domain = check_domain
  1287. def _conn_maker(self, *args, **kwargs):
  1288. """
  1289. This is called to create a connection instance. Normally you'd
  1290. pass a connection class to do_open, but it doesn't actually check for
  1291. a class, and just expects a callable. As long as we behave just as a
  1292. constructor would have, we should be OK. If it ever changes so that
  1293. we *must* pass a class, we'll create an UnsafeHTTPSConnection class
  1294. which just sets check_domain to False in the class definition, and
  1295. choose which one to pass to do_open.
  1296. """
  1297. result = HTTPSConnection(*args, **kwargs)
  1298. if self.ca_certs:
  1299. result.ca_certs = self.ca_certs
  1300. result.check_domain = self.check_domain
  1301. return result
  1302. def https_open(self, req):
  1303. try:
  1304. return self.do_open(self._conn_maker, req)
  1305. except URLError as e:
  1306. if 'certificate verify failed' in str(e.reason):
  1307. raise CertificateError('Unable to verify server certificate '
  1308. 'for %s' % req.host)
  1309. else:
  1310. raise
  1311. #
  1312. # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-
  1313. # Middle proxy using HTTP listens on port 443, or an index mistakenly serves
  1314. # HTML containing a http://xyz link when it should be https://xyz),
  1315. # you can use the following handler class, which does not allow HTTP traffic.
  1316. #
  1317. # It works by inheriting from HTTPHandler - so build_opener won't add a
  1318. # handler for HTTP itself.
  1319. #
  1320. class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):
  1321. def http_open(self, req):
  1322. raise URLError('Unexpected HTTP request on what should be a secure '
  1323. 'connection: %s' % req)
  1324. #
  1325. # XML-RPC with timeouts
  1326. #
  1327. class Transport(xmlrpclib.Transport):
  1328. def __init__(self, timeout, use_datetime=0):
  1329. self.timeout = timeout
  1330. xmlrpclib.Transport.__init__(self, use_datetime)
  1331. def make_connection(self, host):
  1332. h, eh, x509 = self.get_host_info(host)
  1333. if not self._connection or host != self._connection[0]:
  1334. self._extra_headers = eh
  1335. self._connection = host, httplib.HTTPConnection(h)
  1336. return self._connection[1]
  1337. if ssl:
  1338. class SafeTransport(xmlrpclib.SafeTransport):
  1339. def __init__(self, timeout, use_datetime=0):
  1340. self.timeout = timeout
  1341. xmlrpclib.SafeTransport.__init__(self, use_datetime)
  1342. def make_connection(self, host):
  1343. h, eh, kwargs = self.get_host_info(host)
  1344. if not kwargs:
  1345. kwargs = {}
  1346. kwargs['timeout'] = self.timeout
  1347. if not self._connection or host != self._connection[0]:
  1348. self._extra_headers = eh
  1349. self._connection = host, httplib.HTTPSConnection(h, None,
  1350. **kwargs)
  1351. return self._connection[1]
  1352. class ServerProxy(xmlrpclib.ServerProxy):
  1353. def __init__(self, uri, **kwargs):
  1354. self.timeout = timeout = kwargs.pop('timeout', None)
  1355. # The above classes only come into play if a timeout
  1356. # is specified
  1357. if timeout is not None:
  1358. # scheme = splittype(uri) # deprecated as of Python 3.8
  1359. scheme = urlparse(uri)[0]
  1360. use_datetime = kwargs.get('use_datetime', 0)
  1361. if scheme == 'https':
  1362. tcls = SafeTransport
  1363. else:
  1364. tcls = Transport
  1365. kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)
  1366. self.transport = t
  1367. xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)
  1368. #
  1369. # CSV functionality. This is provided because on 2.x, the csv module can't
  1370. # handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.
  1371. #
  1372. def _csv_open(fn, mode, **kwargs):
  1373. if sys.version_info[0] < 3:
  1374. mode += 'b'
  1375. else:
  1376. kwargs['newline'] = ''
  1377. # Python 3 determines encoding from locale. Force 'utf-8'
  1378. # file encoding to match other forced utf-8 encoding
  1379. kwargs['encoding'] = 'utf-8'
  1380. return open(fn, mode, **kwargs)
  1381. class CSVBase(object):
  1382. defaults = {
  1383. 'delimiter': str(','), # The strs are used because we need native
  1384. 'quotechar': str('"'), # str in the csv API (2.x won't take
  1385. 'lineterminator': str('\n') # Unicode)
  1386. }
  1387. def __enter__(self):
  1388. return self
  1389. def __exit__(self, *exc_info):
  1390. self.stream.close()
  1391. class CSVReader(CSVBase):
  1392. def __init__(self, **kwargs):
  1393. if 'stream' in kwargs:
  1394. stream = kwargs['stream']
  1395. if sys.version_info[0] >= 3:
  1396. # needs to be a text stream
  1397. stream = codecs.getreader('utf-8')(stream)
  1398. self.stream = stream
  1399. else:
  1400. self.stream = _csv_open(kwargs['path'], 'r')
  1401. self.reader = csv.reader(self.stream, **self.defaults)
  1402. def __iter__(self):
  1403. return self
  1404. def next(self):
  1405. result = next(self.reader)
  1406. if sys.version_info[0] < 3:
  1407. for i, item in enumerate(result):
  1408. if not isinstance(item, text_type):
  1409. result[i] = item.decode('utf-8')
  1410. return result
  1411. __next__ = next
  1412. class CSVWriter(CSVBase):
  1413. def __init__(self, fn, **kwargs):
  1414. self.stream = _csv_open(fn, 'w')
  1415. self.writer = csv.writer(self.stream, **self.defaults)
  1416. def writerow(self, row):
  1417. if sys.version_info[0] < 3:
  1418. r = []
  1419. for item in row:
  1420. if isinstance(item, text_type):
  1421. item = item.encode('utf-8')
  1422. r.append(item)
  1423. row = r
  1424. self.writer.writerow(row)
  1425. #
  1426. # Configurator functionality
  1427. #
  1428. class Configurator(BaseConfigurator):
  1429. value_converters = dict(BaseConfigurator.value_converters)
  1430. value_converters['inc'] = 'inc_convert'
  1431. def __init__(self, config, base=None):
  1432. super(Configurator, self).__init__(config)
  1433. self.base = base or os.getcwd()
  1434. def configure_custom(self, config):
  1435. def convert(o):
  1436. if isinstance(o, (list, tuple)):
  1437. result = type(o)([convert(i) for i in o])
  1438. elif isinstance(o, dict):
  1439. if '()' in o:
  1440. result = self.configure_custom(o)
  1441. else:
  1442. result = {}
  1443. for k in o:
  1444. result[k] = convert(o[k])
  1445. else:
  1446. result = self.convert(o)
  1447. return result
  1448. c = config.pop('()')
  1449. if not callable(c):
  1450. c = self.resolve(c)
  1451. props = config.pop('.', None)
  1452. # Check for valid identifiers
  1453. args = config.pop('[]', ())
  1454. if args:
  1455. args = tuple([convert(o) for o in args])
  1456. items = [(k, convert(config[k])) for k in config if valid_ident(k)]
  1457. kwargs = dict(items)
  1458. result = c(*args, **kwargs)
  1459. if props:
  1460. for n, v in props.items():
  1461. setattr(result, n, convert(v))
  1462. return result
  1463. def __getitem__(self, key):
  1464. result = self.config[key]
  1465. if isinstance(result, dict) and '()' in result:
  1466. self.config[key] = result = self.configure_custom(result)
  1467. return result
  1468. def inc_convert(self, value):
  1469. """Default converter for the inc:// protocol."""
  1470. if not os.path.isabs(value):
  1471. value = os.path.join(self.base, value)
  1472. with codecs.open(value, 'r', encoding='utf-8') as f:
  1473. result = json.load(f)
  1474. return result
  1475. class SubprocessMixin(object):
  1476. """
  1477. Mixin for running subprocesses and capturing their output
  1478. """
  1479. def __init__(self, verbose=False, progress=None):
  1480. self.verbose = verbose
  1481. self.progress = progress
  1482. def reader(self, stream, context):
  1483. """
  1484. Read lines from a subprocess' output stream and either pass to a progress
  1485. callable (if specified) or write progress information to sys.stderr.
  1486. """
  1487. progress = self.progress
  1488. verbose = self.verbose
  1489. while True:
  1490. s = stream.readline()
  1491. if not s:
  1492. break
  1493. if progress is not None:
  1494. progress(s, context)
  1495. else:
  1496. if not verbose:
  1497. sys.stderr.write('.')
  1498. else:
  1499. sys.stderr.write(s.decode('utf-8'))
  1500. sys.stderr.flush()
  1501. stream.close()
  1502. def run_command(self, cmd, **kwargs):
  1503. p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  1504. stderr=subprocess.PIPE, **kwargs)
  1505. t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
  1506. t1.start()
  1507. t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))
  1508. t2.start()
  1509. p.wait()
  1510. t1.join()
  1511. t2.join()
  1512. if self.progress is not None:
  1513. self.progress('done.', 'main')
  1514. elif self.verbose:
  1515. sys.stderr.write('done.\n')
  1516. return p
  1517. def normalize_name(name):
  1518. """Normalize a python package name a la PEP 503"""
  1519. # https://www.python.org/dev/peps/pep-0503/#normalized-names
  1520. return re.sub('[-_.]+', '-', name).lower()
  1521. # def _get_pypirc_command():
  1522. # """
  1523. # Get the distutils command for interacting with PyPI configurations.
  1524. # :return: the command.
  1525. # """
  1526. # from distutils.core import Distribution
  1527. # from distutils.config import PyPIRCCommand
  1528. # d = Distribution()
  1529. # return PyPIRCCommand(d)
  1530. class PyPIRCFile(object):
  1531. DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
  1532. DEFAULT_REALM = 'pypi'
  1533. def __init__(self, fn=None, url=None):
  1534. if fn is None:
  1535. fn = os.path.join(os.path.expanduser('~'), '.pypirc')
  1536. self.filename = fn
  1537. self.url = url
  1538. def read(self):
  1539. result = {}
  1540. if os.path.exists(self.filename):
  1541. repository = self.url or self.DEFAULT_REPOSITORY
  1542. config = configparser.RawConfigParser()
  1543. config.read(self.filename)
  1544. sections = config.sections()
  1545. if 'distutils' in sections:
  1546. # let's get the list of servers
  1547. index_servers = config.get('distutils', 'index-servers')
  1548. _servers = [server.strip() for server in
  1549. index_servers.split('\n')
  1550. if server.strip() != '']
  1551. if _servers == []:
  1552. # nothing set, let's try to get the default pypi
  1553. if 'pypi' in sections:
  1554. _servers = ['pypi']
  1555. else:
  1556. for server in _servers:
  1557. result = {'server': server}
  1558. result['username'] = config.get(server, 'username')
  1559. # optional params
  1560. for key, default in (('repository', self.DEFAULT_REPOSITORY),
  1561. ('realm', self.DEFAULT_REALM),
  1562. ('password', None)):
  1563. if config.has_option(server, key):
  1564. result[key] = config.get(server, key)
  1565. else:
  1566. result[key] = default
  1567. # work around people having "repository" for the "pypi"
  1568. # section of their config set to the HTTP (rather than
  1569. # HTTPS) URL
  1570. if (server == 'pypi' and
  1571. repository in (self.DEFAULT_REPOSITORY, 'pypi')):
  1572. result['repository'] = self.DEFAULT_REPOSITORY
  1573. elif (result['server'] != repository and
  1574. result['repository'] != repository):
  1575. result = {}
  1576. elif 'server-login' in sections:
  1577. # old format
  1578. server = 'server-login'
  1579. if config.has_option(server, 'repository'):
  1580. repository = config.get(server, 'repository')
  1581. else:
  1582. repository = self.DEFAULT_REPOSITORY
  1583. result = {
  1584. 'username': config.get(server, 'username'),
  1585. 'password': config.get(server, 'password'),
  1586. 'repository': repository,
  1587. 'server': server,
  1588. 'realm': self.DEFAULT_REALM
  1589. }
  1590. return result
  1591. def update(self, username, password):
  1592. # import pdb; pdb.set_trace()
  1593. config = configparser.RawConfigParser()
  1594. fn = self.filename
  1595. config.read(fn)
  1596. if not config.has_section('pypi'):
  1597. config.add_section('pypi')
  1598. config.set('pypi', 'username', username)
  1599. config.set('pypi', 'password', password)
  1600. with open(fn, 'w') as f:
  1601. config.write(f)
  1602. def _load_pypirc(index):
  1603. """
  1604. Read the PyPI access configuration as supported by distutils.
  1605. """
  1606. return PyPIRCFile(url=index.url).read()
  1607. def _store_pypirc(index):
  1608. PyPIRCFile().update(index.username, index.password)
  1609. #
  1610. # get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor
  1611. # tweaks
  1612. #
  1613. def get_host_platform():
  1614. """Return a string that identifies the current platform. This is used mainly to
  1615. distinguish platform-specific build directories and platform-specific built
  1616. distributions. Typically includes the OS name and version and the
  1617. architecture (as supplied by 'os.uname()'), although the exact information
  1618. included depends on the OS; eg. on Linux, the kernel version isn't
  1619. particularly important.
  1620. Examples of returned values:
  1621. linux-i586
  1622. linux-alpha (?)
  1623. solaris-2.6-sun4u
  1624. Windows will return one of:
  1625. win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  1626. win32 (all others - specifically, sys.platform is returned)
  1627. For other non-POSIX platforms, currently just returns 'sys.platform'.
  1628. """
  1629. if os.name == 'nt':
  1630. if 'amd64' in sys.version.lower():
  1631. return 'win-amd64'
  1632. if '(arm)' in sys.version.lower():
  1633. return 'win-arm32'
  1634. if '(arm64)' in sys.version.lower():
  1635. return 'win-arm64'
  1636. return sys.platform
  1637. # Set for cross builds explicitly
  1638. if "_PYTHON_HOST_PLATFORM" in os.environ:
  1639. return os.environ["_PYTHON_HOST_PLATFORM"]
  1640. if os.name != 'posix' or not hasattr(os, 'uname'):
  1641. # XXX what about the architecture? NT is Intel or Alpha,
  1642. # Mac OS is M68k or PPC, etc.
  1643. return sys.platform
  1644. # Try to distinguish various flavours of Unix
  1645. (osname, host, release, version, machine) = os.uname()
  1646. # Convert the OS name to lowercase, remove '/' characters, and translate
  1647. # spaces (for "Power Macintosh")
  1648. osname = osname.lower().replace('/', '')
  1649. machine = machine.replace(' ', '_').replace('/', '-')
  1650. if osname[:5] == 'linux':
  1651. # At least on Linux/Intel, 'machine' is the processor --
  1652. # i386, etc.
  1653. # XXX what about Alpha, SPARC, etc?
  1654. return "%s-%s" % (osname, machine)
  1655. elif osname[:5] == 'sunos':
  1656. if release[0] >= '5': # SunOS 5 == Solaris 2
  1657. osname = 'solaris'
  1658. release = '%d.%s' % (int(release[0]) - 3, release[2:])
  1659. # We can't use 'platform.architecture()[0]' because a
  1660. # bootstrap problem. We use a dict to get an error
  1661. # if some suspicious happens.
  1662. bitness = {2147483647:'32bit', 9223372036854775807:'64bit'}
  1663. machine += '.%s' % bitness[sys.maxsize]
  1664. # fall through to standard osname-release-machine representation
  1665. elif osname[:3] == 'aix':
  1666. from _aix_support import aix_platform
  1667. return aix_platform()
  1668. elif osname[:6] == 'cygwin':
  1669. osname = 'cygwin'
  1670. rel_re = re.compile (r'[\d.]+', re.ASCII)
  1671. m = rel_re.match(release)
  1672. if m:
  1673. release = m.group()
  1674. elif osname[:6] == 'darwin':
  1675. import _osx_support, distutils.sysconfig
  1676. osname, release, machine = _osx_support.get_platform_osx(
  1677. distutils.sysconfig.get_config_vars(),
  1678. osname, release, machine)
  1679. return '%s-%s-%s' % (osname, release, machine)
  1680. _TARGET_TO_PLAT = {
  1681. 'x86' : 'win32',
  1682. 'x64' : 'win-amd64',
  1683. 'arm' : 'win-arm32',
  1684. }
  1685. def get_platform():
  1686. if os.name != 'nt':
  1687. return get_host_platform()
  1688. cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')
  1689. if cross_compilation_target not in _TARGET_TO_PLAT:
  1690. return get_host_platform()
  1691. return _TARGET_TO_PLAT[cross_compilation_target]