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

util.py 58KB

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