desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distrib...
def require(self, *requirements):
needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
'Invoke `callback` for all distributions (including existing ones)'
def subscribe(self, callback):
if (callback in self.callbacks): return self.callbacks.append(callback) for dist in self: callback(dist)
'Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distribu...
def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
self._distmap = {} self._cache = {} self.platform = platform self.python = python self.scan(search_path)
'Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned.'
def can_add(self, dist):
return (((self.python is None) or (dist.py_version is None) or (dist.py_version == self.python)) and compatible_platforms(dist.platform, self.platform))
'Remove `dist` from the environment'
def remove(self, dist):
self._distmap[dist.key].remove(dist)
'Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added.'
def scan(self, search_path=None):
if (search_path is None): search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
'Return a newest-to-oldest list of distributions for `project_name`'
def __getitem__(self, project_name):
try: return self._cache[project_name] except KeyError: project_name = project_name.lower() if (project_name not in self._distmap): return [] if (project_name not in self._cache): dists = self._cache[project_name] = self._distmap[project_name] _sort_dists(d...
'Add `dist` if we ``can_add()`` it and it isn\'t already added'
def add(self, dist):
if (self.can_add(dist) and dist.has_version()): dists = self._distmap.setdefault(dist.key, []) if (dist not in dists): dists.append(dist) if (dist.key in self._cache): _sort_dists(self._cache[dist.key])
'Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable ...
def best_match(self, req, working_set, installer=None):
dist = working_set.find(req) if (dist is not None): return dist for dist in self[req.key]: if (dist in req): return dist return self.obtain(req, installer)
'Obtain a distribution matching `requirement` (e.g. via download) Obtain a distro that matches requirement (e.g. via download). In the base ``Environment`` class, this routine just returns ``installer(requirement)``, unless `installer` is None, in which case None is returned instead. This method is a hook that allows...
def obtain(self, requirement, installer=None):
if (installer is not None): return installer(requirement)
'Yield the unique project names of the available distributions'
def __iter__(self):
for key in self._distmap.keys(): if self[key]: (yield key)
'In-place addition of a distribution or environment'
def __iadd__(self, other):
if isinstance(other, Distribution): self.add(other) elif isinstance(other, Environment): for project in other: for dist in other[project]: self.add(dist) else: raise TypeError(("Can't add %r to environment" % (other,))) return self
'Add an environment or distribution to an environment'
def __add__(self, other):
new = self.__class__([], platform=None, python=None) for env in (self, other): new += env return new
'Does the named resource exist?'
def resource_exists(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).has_resource(resource_name)
'Is the named resource an existing directory?'
def resource_isdir(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).resource_isdir(resource_name)
'Return a true filesystem path for specified resource'
def resource_filename(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).get_resource_filename(self, resource_name)
'Return a readable file-like object for specified resource'
def resource_stream(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).get_resource_stream(self, resource_name)
'Return specified resource as a string'
def resource_string(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).get_resource_string(self, resource_name)
'List the contents of the named resource directory'
def resource_listdir(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).resource_listdir(resource_name)
'Give an error message for problems extracting file(s)'
def extraction_error(self):
old_exc = sys.exc_info()[1] cache_path = (self.extraction_path or get_default_cache()) err = ExtractionError(("Can't extract file(s) to egg cache\n\nThe following error occurred while trying to extract file(s) to the Python egg\ncache:\n\n %s\n\nThe ...
'Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if ...
def get_cache_path(self, archive_name, names=()):
extract_path = (self.extraction_path or get_default_cache()) target_path = os.path.join(extract_path, (archive_name + '-tmp'), *names) try: _bypass_ensure_directory(target_path) except: self.extraction_error() self._warn_unsafe_extraction_path(extract_path) self.cached_files[targ...
'If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details.'
@staticmethod def _warn_unsafe_extraction_path(path):
if ((os.name == 'nt') and (not path.startswith(os.environ['windir']))): return mode = os.stat(path).st_mode if ((mode & stat.S_IWOTH) or (mode & stat.S_IWGRP)): msg = ('%s is writable by group/others and vulnerable to attack when used with get_resource_fil...
'Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don\'t have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are alr...
def postprocess(self, tempname, filename):
if (os.name == 'posix'): mode = ((os.stat(tempname).st_mode | 365) & 4095) os.chmod(tempname, mode)
'Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that ...
def set_extraction_path(self, path):
if self.cached_files: raise ValueError("Can't change extraction path, files already extracted") self.extraction_path = path
'Validate text as a PEP 426 environment marker; return an exception if invalid or False otherwise.'
@classmethod def is_invalid_marker(cls, text):
try: cls.evaluate_marker(text) except SyntaxError: return cls.normalize_exception(sys.exc_info()[1]) return False
'Given a SyntaxError from a marker evaluation, normalize the error message: - Remove indications of filename and line number. - Replace platform-specific error messages with standard error messages.'
@staticmethod def normalize_exception(exc):
subs = {'unexpected EOF while parsing': 'invalid syntax', 'parenthesis is never closed': 'invalid syntax'} exc.filename = None exc.lineno = None exc.msg = subs.get(exc.msg, exc.msg) return exc
'Evaluate a PEP 426 environment marker on CPython 2.4+. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. This implementation uses the \'parser\' module, which is not implemented on Jython and has been superseded by the \'ast\' module in Python 2.6 and later.'
@classmethod def evaluate_marker(cls, text, extra=None):
return cls.interpret(parser.expr(text).totuple(1)[1])
'Evaluate a PEP 426 environment marker using markerlib. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid.'
@classmethod def _markerlib_evaluate(cls, text):
from pip._vendor import _markerlib env = _markerlib.default_environment() for key in env.keys(): new_key = key.replace('.', '_') env[new_key] = env.pop(key) try: result = _markerlib.interpret(text, env) except NameError: e = sys.exc_info()[1] raise SyntaxError...
'Return True if the file_path is current for this zip_path'
def _is_current(self, file_path, zip_path):
(timestamp, size) = self._get_date_and_size(self.zipinfo[zip_path]) if (not os.path.isfile(file_path)): return False stat = os.stat(file_path) if ((stat.st_size != size) or (stat.st_mtime != timestamp)): return False zip_contents = self.loader.get_data(zip_path) f = open(file_pat...
'Create a metadata provider from a zipimporter'
def __init__(self, importer):
self.zipinfo = build_zipmanifest(importer.archive) self.zip_pre = (importer.archive + os.sep) self.loader = importer if importer.prefix: self.module_path = os.path.join(importer.archive, importer.prefix) else: self.module_path = importer.archive self._setup_prefix()
'Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1,extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional'
@classmethod def parse(cls, src, dist=None):
try: attrs = extras = () (name, value) = src.split('=', 1) if ('[' in value): (value, extras) = value.split('[', 1) req = Requirement.parse(('x[' + extras)) if req.specs: raise ValueError extras = req.extras if (':' in v...
'Parse an entry point group'
@classmethod def parse_group(cls, group, lines, dist=None):
if (not MODULE(group)): raise ValueError('Invalid group name', group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if (ep.name in this): raise ValueError('Duplicate entry point', group, ep.name) this[ep.name] = ep return thi...
'Parse a map of entry point groups'
@classmethod def parse_map(cls, data, dist=None):
if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for (group, lines) in data: if (group is None): if (not lines): continue raise ValueError('Entry points must be listed in groups') ...
'List of Requirements needed for this distro if `extras` are used'
def requires(self, extras=()):
dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra(('%s has no such extra feature %r' % (self, ext))) return deps
'Ensure distribution is importable on `path` (default=sys.path)'
def activate(self, path=None):
if (path is None): path = sys.path self.insert_on(path) if (path is sys.path): fixup_namespace_packages(self.location) for pkg in self._get_metadata('namespace_packages.txt'): if (pkg in sys.modules): declare_namespace(pkg)
'Return what this distribution\'s standard .egg filename should be'
def egg_name(self):
filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR))) if self.platform: filename += ('-' + self.platform) return filename
'Delegate all unrecognized public attributes to .metadata provider'
def __getattr__(self, attr):
if attr.startswith('_'): raise AttributeError(attr) return getattr(self._provider, attr)
'Return a ``Requirement`` that matches this distribution exactly'
def as_requirement(self):
return Requirement.parse(('%s==%s' % (self.project_name, self.version)))
'Return the `name` entry point of `group` or raise ImportError'
def load_entry_point(self, group, name):
ep = self.get_entry_info(group, name) if (ep is None): raise ImportError(('Entry point %r not found' % ((group, name),))) return ep.load()
'Return the entry point map for `group`, or the full entry map'
def get_entry_map(self, group=None):
try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self) if (group is not None): return ep_map.get(group, {}) return ep_map
'Return the EntryPoint object for `group`+`name`, or ``None``'
def get_entry_info(self, group, name):
return self.get_entry_map(group).get(name)
'Insert self.location in path before its nearest parent directory'
def insert_on(self, path, loc=None):
loc = (loc or self.location) if (not loc): return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [((p and _normalize_cached(p)) or p) for p in path] for (p, item) in enumerate(npath): if (item == nloc): break elif ((item == bdir) and (self....
'Copy this distribution, substituting in any changed keyword args'
def clone(self, **kw):
for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
'Parse and cache metadata'
@property def _parsed_pkg_info(self):
try: return self._pkg_info except AttributeError: from email.parser import Parser self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO)) return self._pkg_info
'Convert \'Foobar (1); baz\' to (\'Foobar ==1\', \'baz\') Split environment marker, add == prefix to version specifiers as necessary, and remove parenthesis.'
def _preparse_requirement(self, requires_dist):
parts = (requires_dist.split(';', 1) + ['']) distvers = parts[0].strip() mark = parts[1].strip() distvers = re.sub(self.EQEQ, '\\1==\\2\\3', distvers) distvers = distvers.replace('(', '').replace(')', '') return (distvers, mark)
'Recompute this distribution\'s dependencies.'
def _compute_dependencies(self):
from pip._vendor._markerlib import compile as compile_marker dm = self.__dep_map = {None: []} reqs = [] for req in (self._parsed_pkg_info.get_all('Requires-Dist') or []): (distvers, mark) = self._preparse_requirement(req) parsed = next(parse_requirements(distvers)) parsed.marker_...
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
def __init__(self, project_name, specs, extras):
(self.unsafe_name, project_name) = (project_name, safe_name(project_name)) (self.project_name, self.key) = (project_name, project_name.lower()) index = [(parse_version(v), state_machine[op], op, v) for (op, v) in specs] index.sort() self.specs = [(op, ver) for (parsed, trans, op, ver) in index] ...
'This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested.'
def __iter__(self):
self.tokenQueue = deque([]) while self.state(): while self.stream.errors: (yield {u'type': tokenTypes[u'ParseError'], u'data': self.stream.errors.pop(0)}) while self.tokenQueue: (yield self.tokenQueue.popleft())
'This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.'
def consumeNumberEntity(self, isHex):
allowed = digits radix = 10 if isHex: allowed = hexDigits radix = 16 charStack = [] c = self.stream.char() while ((c in allowed) and (c is not EOF)): charStack.append(c) c = self.stream.char() charAsInt = int(u''.join(charStack), radix) if (charAsInt in re...
'This method replaces the need for "entityInAttributeValueState".'
def processEntityInAttribute(self, allowedChar):
self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
'This method is a generic handler for emitting the tags. It also sets the state to "data" because that\'s what\'s needed after a token has been emitted.'
def emitCurrentToken(self):
token = self.currentToken if (token[u'type'] in tagTokenTypes): if self.lowercaseElementName: token[u'name'] = token[u'name'].translate(asciiUpper2Lower) if (token[u'type'] == tokenTypes[u'EndTag']): if token[u'data']: self.tokenQueue.append({u'type': toke...
'Initialize HTMLSerializer. Keyword options (default given first unless specified) include: inject_meta_charset=True|False Whether it insert a meta element to define the character set of the document. quote_attr_values=True|False Whether to quote attribute values that don\'t require quoting per HTML5 parsing rules. quo...
def __init__(self, **kwargs):
if (u'quote_char' in kwargs): self.use_best_quote_char = False for attr in self.options: setattr(self, attr, kwargs.get(attr, getattr(self, attr))) self.errors = [] self.strict = False
'Node representing an item in the tree. name - The tag name associated with the node parent - The parent of the current node (or None for the document node) value - The value of the current node (applies to text nodes and comments attributes - a dict holding name, value pairs for attributes of the node childNodes - a l...
def __init__(self, name):
self.name = name self.parent = None self.value = None self.attributes = {} self.childNodes = [] self._flags = []
'Insert node as a child of the current node'
def appendChild(self, node):
raise NotImplementedError
'Insert data as text in the current node, positioned before the start of node insertBefore or to the end of the node\'s text.'
def insertText(self, data, insertBefore=None):
raise NotImplementedError
'Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node'
def insertBefore(self, node, refNode):
raise NotImplementedError
'Remove node from the children of the current node'
def removeChild(self, node):
raise NotImplementedError
'Move all the children of the current node to newParent. This is needed so that trees that don\'t store text as nodes move the text in the correct way'
def reparentChildren(self, newParent):
for child in self.childNodes: newParent.appendChild(child) self.childNodes = []
'Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes'
def cloneNode(self):
raise NotImplementedError
'Return true if the node has children or text, false otherwise'
def hasContent(self):
raise NotImplementedError
'Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false'
def elementInActiveFormattingElements(self, name):
for item in self.activeFormattingElements[::(-1)]: if (item == Marker): break elif (item.name == name): return item return False
'Create an element but don\'t insert it anywhere'
def createElement(self, token):
name = token[u'name'] namespace = token.get(u'namespace', self.defaultNamespace) element = self.elementClass(name, namespace) element.attributes = token[u'data'] return element
'Switch the function used to insert an element from the normal one to the misnested table one and back again'
def _setInsertFromTable(self, value):
self._insertFromTable = value if value: self.insertElement = self.insertElementTable else: self.insertElement = self.insertElementNormal
'Create an element and insert it into the tree'
def insertElementTable(self, token):
element = self.createElement(token) if (self.openElements[(-1)].name not in tableInsertModeElements): return self.insertElementNormal(token) else: (parent, insertBefore) = self.getTableMisnestedNodePosition() if (insertBefore is None): parent.appendChild(element) ...
'Insert text data.'
def insertText(self, data, parent=None):
if (parent is None): parent = self.openElements[(-1)] if ((not self.insertFromTable) or (self.insertFromTable and (self.openElements[(-1)].name not in tableInsertModeElements))): parent.insertText(data) else: (parent, insertBefore) = self.getTableMisnestedNodePosition() paren...
'Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node'
def getTableMisnestedNodePosition(self):
lastTable = None fosterParent = None insertBefore = None for elm in self.openElements[::(-1)]: if (elm.name == u'table'): lastTable = elm break if lastTable: if lastTable.parent: fosterParent = lastTable.parent insertBefore = lastTable ...
'Return the final tree'
def getDocument(self):
return self.document
'Return the final fragment'
def getFragment(self):
fragment = self.fragmentClass() self.openElements[0].reparentChildren(fragment) return fragment
'Serialize the subtree of node in the format required by unit tests node - the node from which to start serializing'
def testSerializer(self, node):
raise NotImplementedError
'Create the document root'
def insertRoot(self, token):
docStr = u'' if self.doctype: assert self.doctype.name docStr += (u'<!DOCTYPE %s' % self.doctype.name) if ((self.doctype.publicId is not None) or (self.doctype.systemId is not None)): docStr += (u' PUBLIC "%s" ' % self.infosetFilter.coercePubid((self.doctype.publi...
'strict - raise an exception when a parse error is encountered tree - a treebuilder class controlling the type of tree that will be returned. Built in treebuilders can be accessed through html5lib.treebuilders.getTreeBuilder(treeType) tokenizer - a class that provides a stream of tokens to the treebuilder. This may be ...
def __init__(self, tree=None, tokenizer=tokenizer.HTMLTokenizer, strict=False, namespaceHTMLElements=True, debug=False):
self.strict = strict if (tree is None): tree = treebuilders.getTreeBuilder(u'etree') self.tree = tree(namespaceHTMLElements) self.tokenizer_class = tokenizer self.errors = [] self.phases = dict([(name, cls(self, self.tree)) for (name, cls) in getPhases(debug).items()])
'Parse a HTML document into a well-formed tree stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element)'
def parse(self, stream, encoding=None, parseMeta=True, useChardet=True):
self._parse(stream, innerHTML=False, encoding=encoding, parseMeta=parseMeta, useChardet=useChardet) return self.tree.getDocument()
'Parse a HTML fragment into a well-formed tree fragment container - name of the element we\'re setting the innerHTML property if set to None, default to \'div\' stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specifi...
def parseFragment(self, stream, container=u'div', encoding=None, parseMeta=False, useChardet=True):
self._parse(stream, True, container=container, encoding=encoding) return self.tree.getFragment()
'HTML5 specific normalizations to the token stream'
def normalizeToken(self, token):
if (token[u'type'] == tokenTypes[u'StartTag']): token[u'data'] = dict(token[u'data'][::(-1)]) return token
'Generic RCDATA/RAWTEXT Parsing algorithm contentType - RCDATA or RAWTEXT'
def parseRCDataRawtext(self, token, contentType):
assert (contentType in (u'RAWTEXT', u'RCDATA')) self.tree.insertElement(token) if (contentType == u'RAWTEXT'): self.tokenizer.state = self.tokenizer.rawtextState else: self.tokenizer.state = self.tokenizer.rcdataState self.originalPhase = self.phase self.phase = self.phases[u'tex...
'Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless ...
def __init__(self, source):
if (len(u'\U0010ffff') == 1): self.reportCharacterErrors = self.characterErrorsUCS4 self.replaceCharactersRegexp = re.compile(u'[\ud800-\udfff]') else: self.reportCharacterErrors = self.characterErrorsUCS2 self.replaceCharactersRegexp = re.compile(u'([\ud800-\udbff](?![\udc00-\ud...
'Produces a file object from source. source can be either a file object, local filename or a string.'
def openStream(self, source):
if hasattr(source, u'read'): stream = source else: stream = StringIO(source) return stream
'Returns (line, col) of the current position in the stream.'
def position(self):
(line, col) = self._position(self.chunkOffset) return ((line + 1), col)
'Read one character from the stream or queue if available. Return EOF when EOF is reached.'
def char(self):
if (self.chunkOffset >= self.chunkSize): if (not self.readChunk()): return EOF chunkOffset = self.chunkOffset char = self.chunk[chunkOffset] self.chunkOffset = (chunkOffset + 1) return char
'Returns a string of characters from the stream up to but not including any character in \'characters\' or EOF. \'characters\' must be a container that supports the \'in\' method and iteration over its characters.'
def charsUntil(self, characters, opposite=False):
try: chars = charsUntilRegEx[(characters, opposite)] except KeyError: if __debug__: for c in characters: assert (ord(c) < 128) regex = u''.join([(u'\\x%02x' % ord(c)) for c in characters]) if (not opposite): regex = (u'^%s' % regex) ...
'Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless ...
def __init__(self, source, encoding=None, parseMeta=True, chardet=True):
self.rawStream = self.openStream(source) HTMLUnicodeInputStream.__init__(self, self.rawStream) self.charEncoding = (codecName(encoding), u'certain') self.numBytesMeta = 512 self.numBytesChardet = 100 self.defaultEncoding = u'windows-1252' if (self.charEncoding[0] is None): self.charE...
'Produces a file object from source. source can be either a file object, local filename or a string.'
def openStream(self, source):
if hasattr(source, u'read'): stream = source else: stream = BytesIO(source) try: stream.seek(stream.tell()) except: stream = BufferedStream(stream) return stream
'Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None'
def detectBOM(self):
bomDict = {codecs.BOM_UTF8: u'utf-8', codecs.BOM_UTF16_LE: u'utf-16-le', codecs.BOM_UTF16_BE: u'utf-16-be', codecs.BOM_UTF32_LE: u'utf-32-le', codecs.BOM_UTF32_BE: u'utf-32-be'} string = self.rawStream.read(4) assert isinstance(string, bytes) encoding = bomDict.get(string[:3]) seek = 3 if (not e...
'Report the encoding declared by the meta element'
def detectEncodingMeta(self):
buffer = self.rawStream.read(self.numBytesMeta) assert isinstance(buffer, bytes) parser = EncodingParser(buffer) self.rawStream.seek(0) encoding = parser.getEncoding() if (encoding in (u'utf-16', u'utf-16-be', u'utf-16-le')): encoding = u'utf-8' return encoding
'Skip past a list of characters'
def skip(self, chars=spaceCharactersBytes):
p = self.position while (p < len(self)): c = self[p:(p + 1)] if (c not in chars): self._position = p return c p += 1 self._position = p return None
'Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone'
def matchBytes(self, bytes):
p = self.position data = self[p:(p + len(bytes))] rv = data.startswith(bytes) if rv: self.position += len(bytes) return rv
'Look for the next sequence of bytes matching a given sequence. If a match is found advance the position to the last byte of the match'
def jumpTo(self, bytes):
newPosition = self[self.position:].find(bytes) if (newPosition > (-1)): if (self._position == (-1)): self._position = 0 self._position += ((newPosition + len(bytes)) - 1) return True else: raise StopIteration
'string - the data to work on for encoding detection'
def __init__(self, data):
self.data = EncodingBytes(data) self.encoding = None
'Skip over comments'
def handleComment(self):
return self.data.jumpTo('-->')
'Return a name,value pair for the next attribute in the stream, if one is found, or None'
def getAttribute(self):
data = self.data c = data.skip((spaceCharactersBytes | frozenset(['/']))) assert ((c is None) or (len(c) == 1)) if (c in ('>', None)): return None attrName = [] attrValue = [] while True: if ((c == '=') and attrName): break elif (c in spaceCharactersBytes)...
'Initialise an instance. :param url: The URL of the index. If not specified, the URL for PyPI is used.'
def __init__(self, url=None):
self.url = (url or DEFAULT_INDEX) self.read_configuration() (scheme, netloc, path, params, query, frag) = urlparse(self.url) if (params or query or frag or (scheme not in ('http', 'https'))): raise DistlibException(('invalid repository: %s' % self.url)) self.password_handler = None ...
'Get the distutils command for interacting with PyPI configurations. :return: the command.'
def _get_pypirc_command(self):
from distutils.core import Distribution from distutils.config import PyPIRCCommand d = Distribution() return PyPIRCCommand(d)
'Read the PyPI access configuration as supported by distutils, getting PyPI to do the acutal work. This populates ``username``, ``password``, ``realm`` and ``url`` attributes from the configuration.'
def read_configuration(self):
c = self._get_pypirc_command() c.repository = self.url cfg = c._read_pypirc() self.username = cfg.get('username') self.password = cfg.get('password') self.realm = cfg.get('realm', 'pypi') self.url = cfg.get('repository', self.url)
'Save the PyPI access configuration. You must have set ``username`` and ``password`` attributes before calling this method. Again, distutils is used to do the actual work.'
def save_configuration(self):
self.check_credentials() c = self._get_pypirc_command() c._store_pypirc(self.username, self.password)
'Check that ``username`` and ``password`` have been set, and raise an exception if not.'
def check_credentials(self):
if ((self.username is None) or (self.password is None)): raise DistlibException('username and password must be set') pm = HTTPPasswordMgr() (_, netloc, _, _, _, _) = urlparse(self.url) pm.add_password(self.realm, netloc, self.username, self.password) self.password_handler = HT...
'Register a distribution on PyPI, using the provided metadata. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the distribution to be registered. :return: The HTTP response received from PyPI upon submission of the request.'
def register(self, metadata):
self.check_credentials() metadata.validate() d = metadata.todict() d[':action'] = 'verify' request = self.encode_request(d.items(), []) response = self.send_request(request) d[':action'] = 'submit' request = self.encode_request(d.items(), []) return self.send_request(request)
'Thread runner for reading lines of from a subprocess into a buffer. :param name: The logical name of the stream (used for logging only). :param stream: The stream to read from. This will typically a pipe connected to the output stream of a subprocess. :param outbuf: The list to append the read lines to.'
def _reader(self, name, stream, outbuf):
while True: s = stream.readline() if (not s): break s = s.decode('utf-8').rstrip() outbuf.append(s) logger.debug(('%s: %s' % (name, s))) stream.close()
'Return a suitable command for signing a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer\'s private key used for signing. :return: The signing command as a list suitable to be passed to :class:`sub...
def get_sign_command(self, filename, signer, sign_password):
cmd = [self.gpg, '--status-fd', '2', '--no-tty'] if self.gpg_home: cmd.extend(['--homedir', self.gpg_home]) if (sign_password is not None): cmd.extend(['--batch', '--passphrase-fd', '0']) td = tempfile.mkdtemp() sf = os.path.join(td, (os.path.basename(filename) + '.asc')) cmd.ext...
'Run a command in a child process , passing it any input data specified. :param cmd: The command to run. :param input_data: If specified, this must be a byte string containing data to be sent to the child process. :return: A tuple consisting of the subprocess\' exit code, a list of lines read from the subprocess\' ``st...
def run_command(self, cmd, input_data=None):
kwargs = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE} if (input_data is not None): kwargs['stdin'] = subprocess.PIPE stdout = [] stderr = [] p = subprocess.Popen(cmd, **kwargs) t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout)) t1.start() t2 = Thread(ta...
'Sign a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer\'s private key used for signing. :return: The absolute pathname of the file where the signature is stored.'
def sign_file(self, filename, signer, sign_password):
(cmd, sig_file) = self.get_sign_command(filename, signer, sign_password) (rc, stdout, stderr) = self.run_command(cmd, sign_password.encode('utf-8')) if (rc != 0): raise DistlibException(('sign command failed with error code %s' % rc)) return sig_file