text
stringlengths
81
112k
This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT). def close(self, force=True): '''This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT). ''' if not self.closed: self.flush() self.fileobj.close() # Closes the file descriptor # Give kernel time to update process status. time.sleep(self.delayafterclose) if self.isalive(): if not self.terminate(force): raise PtyProcessError('Could not terminate the child.') self.fd = -1 self.closed = True
This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). Not supported on platforms where ``isatty()`` returns False. def getecho(self): '''This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). Not supported on platforms where ``isatty()`` returns False. ''' try: attr = termios.tcgetattr(self.fd) except termios.error as err: errmsg = 'getecho() may not be called on this platform' if err.args[0] == errno.EINVAL: raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg)) raise self.echo = bool(attr[3] & termios.ECHO) return self.echo
This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') # Echo is on by default. p.sendline('1234') # We expect see this twice from the child... p.expect(['1234']) # ... once from the tty echo... p.expect(['1234']) # ... and again from cat itself. p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['abcd']) p.expect(['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline('1234') p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['1234']) p.expect(['1234']) p.expect(['abcd']) p.expect(['wxyz']) Not supported on platforms where ``isatty()`` returns False. def setecho(self, state): '''This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') # Echo is on by default. p.sendline('1234') # We expect see this twice from the child... p.expect(['1234']) # ... once from the tty echo... p.expect(['1234']) # ... and again from cat itself. p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['abcd']) p.expect(['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline('1234') p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['1234']) p.expect(['1234']) p.expect(['abcd']) p.expect(['wxyz']) Not supported on platforms where ``isatty()`` returns False. ''' _setecho(self.fd, state) self.echo = state
Read and return at most ``size`` bytes from the pty. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal with the vagaries of EOF on platforms that do strange things, like IRIX or older Solaris systems. It handles the errno=EIO pattern used on Linux, and the empty-string return used on BSD platforms and (seemingly) on recent Solaris. def read(self, size=1024): """Read and return at most ``size`` bytes from the pty. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal with the vagaries of EOF on platforms that do strange things, like IRIX or older Solaris systems. It handles the errno=EIO pattern used on Linux, and the empty-string return used on BSD platforms and (seemingly) on recent Solaris. """ try: s = self.fileobj.read1(size) except (OSError, IOError) as err: if err.args[0] == errno.EIO: # Linux-style EOF self.flag_eof = True raise EOFError('End Of File (EOF). Exception style platform.') raise if s == b'': # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana)) self.flag_eof = True raise EOFError('End Of File (EOF). Empty string style platform.') return s
Read one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. def readline(self): """Read one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. """ try: s = self.fileobj.readline() except (OSError, IOError) as err: if err.args[0] == errno.EIO: # Linux-style EOF self.flag_eof = True raise EOFError('End Of File (EOF). Exception style platform.') raise if s == b'': # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana)) self.flag_eof = True raise EOFError('End Of File (EOF). Empty string style platform.') return s
Write bytes to the pseudoterminal. Returns the number of bytes written. def write(self, s, flush=True): """Write bytes to the pseudoterminal. Returns the number of bytes written. """ return self._writeb(s, flush=flush)
Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof(). def sendcontrol(self, char): '''Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof(). ''' char = char.lower() a = ord(char) if 97 <= a <= 122: a = a - ord('a') + 1 byte = _byte(a) return self._writeb(byte), byte d = {'@': 0, '`': 0, '[': 27, '{': 27, '\\': 28, '|': 28, ']': 29, '}': 29, '^': 30, '~': 30, '_': 31, '?': 127} if char not in d: return 0, b'' byte = _byte(d[char]) return self._writeb(byte), byte
This forces a child process to terminate. It starts nicely with SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This returns True if the child was terminated. This returns False if the child could not be terminated. def terminate(self, force=False): '''This forces a child process to terminate. It starts nicely with SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This returns True if the child was terminated. This returns False if the child could not be terminated. ''' if not self.isalive(): return True try: self.kill(signal.SIGHUP) time.sleep(self.delayafterterminate) if not self.isalive(): return True self.kill(signal.SIGCONT) time.sleep(self.delayafterterminate) if not self.isalive(): return True self.kill(signal.SIGINT) time.sleep(self.delayafterterminate) if not self.isalive(): return True if force: self.kill(signal.SIGKILL) time.sleep(self.delayafterterminate) if not self.isalive(): return True else: return False return False except OSError: # I think there are kernel timing issues that sometimes cause # this to happen. I think isalive() reports True, but the # process is dead to the kernel. # Make one last attempt to see if the kernel is up to date. time.sleep(self.delayafterterminate) if not self.isalive(): return True else: return False
This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is technically still alive until its output is read by the parent. def wait(self): '''This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is technically still alive until its output is read by the parent. ''' if self.isalive(): pid, status = os.waitpid(self.pid, 0) else: return self.exitstatus self.exitstatus = os.WEXITSTATUS(status) if os.WIFEXITED(status): self.status = status self.exitstatus = os.WEXITSTATUS(status) self.signalstatus = None self.terminated = True elif os.WIFSIGNALED(status): self.status = status self.exitstatus = None self.signalstatus = os.WTERMSIG(status) self.terminated = True elif os.WIFSTOPPED(status): # pragma: no cover # You can't call wait() on a child process in the stopped state. raise PtyProcessError('Called wait() on a stopped child ' + 'process. This is not supported. Is some other ' + 'process attempting job control with our child pid?') return self.exitstatus
This tests if the child process is running or not. This is non-blocking. If the child was terminated then this will read the exitstatus or signalstatus of the child. This returns True if the child process appears to be running or False if not. It can take literally SECONDS for Solaris to return the right status. def isalive(self): '''This tests if the child process is running or not. This is non-blocking. If the child was terminated then this will read the exitstatus or signalstatus of the child. This returns True if the child process appears to be running or False if not. It can take literally SECONDS for Solaris to return the right status. ''' if self.terminated: return False if self.flag_eof: # This is for Linux, which requires the blocking form # of waitpid to get the status of a defunct process. # This is super-lame. The flag_eof would have been set # in read_nonblocking(), so this should be safe. waitpid_options = 0 else: waitpid_options = os.WNOHANG try: pid, status = os.waitpid(self.pid, waitpid_options) except OSError as e: # No child processes if e.errno == errno.ECHILD: raise PtyProcessError('isalive() encountered condition ' + 'where "terminated" is 0, but there was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') else: raise # I have to do this twice for Solaris. # I can't even believe that I figured this out... # If waitpid() returns 0 it means that no child process # wishes to report, and the value of status is undefined. if pid == 0: try: ### os.WNOHANG) # Solaris! pid, status = os.waitpid(self.pid, waitpid_options) except OSError as e: # pragma: no cover # This should never happen... if e.errno == errno.ECHILD: raise PtyProcessError('isalive() encountered condition ' + 'that should never happen. There was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') else: raise # If pid is still 0 after two calls to waitpid() then the process # really is alive. This seems to work on all platforms, except for # Irix which seems to require a blocking call on waitpid or select, # so I let read_nonblocking take care of this situation # (unfortunately, this requires waiting through the timeout). if pid == 0: return True if pid == 0: return True if os.WIFEXITED(status): self.status = status self.exitstatus = os.WEXITSTATUS(status) self.signalstatus = None self.terminated = True elif os.WIFSIGNALED(status): self.status = status self.exitstatus = None self.signalstatus = os.WTERMSIG(status) self.terminated = True elif os.WIFSTOPPED(status): raise PtyProcessError('isalive() encountered condition ' + 'where child process is stopped. This is not ' + 'supported. Is some other process attempting ' + 'job control with our child pid?') return False
Send the given signal to the child application. In keeping with UNIX tradition it has a misleading name. It does not necessarily kill the child unless you send the right signal. See the :mod:`signal` module for constants representing signal numbers. def kill(self, sig): """Send the given signal to the child application. In keeping with UNIX tradition it has a misleading name. It does not necessarily kill the child unless you send the right signal. See the :mod:`signal` module for constants representing signal numbers. """ # Same as os.kill, but the pid is given for you. if self.isalive(): os.kill(self.pid, sig)
Read at most ``size`` bytes from the pty, return them as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. The size argument still refers to bytes, not unicode code points. def read(self, size=1024): """Read at most ``size`` bytes from the pty, return them as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. The size argument still refers to bytes, not unicode code points. """ b = super(PtyProcessUnicode, self).read(size) return self.decoder.decode(b, final=False)
Read one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. def readline(self): """Read one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. """ b = super(PtyProcessUnicode, self).readline() return self.decoder.decode(b, final=False)
Write the unicode string ``s`` to the pseudoterminal. Returns the number of bytes written. def write(self, s): """Write the unicode string ``s`` to the pseudoterminal. Returns the number of bytes written. """ b = s.encode(self.encoding) return super(PtyProcessUnicode, self).write(b)
Build an instance from a requirement. def from_requirement(cls, provider, requirement, parent): """Build an instance from a requirement. """ candidates = provider.find_matches(requirement) if not candidates: raise NoVersionsAvailable(requirement, parent) return cls( candidates=candidates, information=[RequirementInformation(requirement, parent)], )
Build a new instance from this and a new requirement. def merged_with(self, provider, requirement, parent): """Build a new instance from this and a new requirement. """ infos = list(self.information) infos.append(RequirementInformation(requirement, parent)) candidates = [ c for c in self.candidates if provider.is_satisfied_by(requirement, c) ] if not candidates: raise RequirementsConflicted(self) return type(self)(candidates, infos)
Push a new state into history. This new state will be used to hold resolution results of the next coming round. def _push_new_state(self): """Push a new state into history. This new state will be used to hold resolution results of the next coming round. """ try: base = self._states[-1] except IndexError: graph = DirectedGraph() graph.add(None) # Sentinel as root dependencies' parent. state = State(mapping={}, graph=graph) else: state = State( mapping=base.mapping.copy(), graph=base.graph.copy(), ) self._states.append(state)
Take a collection of constraints, spit out the resolution result. The return value is a representation to the final resolution result. It is a tuple subclass with two public members: * `mapping`: A dict of resolved candidates. Each key is an identifier of a requirement (as returned by the provider's `identify` method), and the value is the resolved candidate. * `graph`: A `DirectedGraph` instance representing the dependency tree. The vertices are keys of `mapping`, and each edge represents *why* a particular package is included. A special vertex `None` is included to represent parents of user-supplied requirements. The following exceptions may be raised if a resolution cannot be found: * `NoVersionsAvailable`: A requirement has no available candidates. * `ResolutionImpossible`: A resolution cannot be found for the given combination of requirements. * `ResolutionTooDeep`: The dependency tree is too deeply nested and the resolver gave up. This is usually caused by a circular dependency, but you can try to resolve this by increasing the `max_rounds` argument. def resolve(self, requirements, max_rounds=20): """Take a collection of constraints, spit out the resolution result. The return value is a representation to the final resolution result. It is a tuple subclass with two public members: * `mapping`: A dict of resolved candidates. Each key is an identifier of a requirement (as returned by the provider's `identify` method), and the value is the resolved candidate. * `graph`: A `DirectedGraph` instance representing the dependency tree. The vertices are keys of `mapping`, and each edge represents *why* a particular package is included. A special vertex `None` is included to represent parents of user-supplied requirements. The following exceptions may be raised if a resolution cannot be found: * `NoVersionsAvailable`: A requirement has no available candidates. * `ResolutionImpossible`: A resolution cannot be found for the given combination of requirements. * `ResolutionTooDeep`: The dependency tree is too deeply nested and the resolver gave up. This is usually caused by a circular dependency, but you can try to resolve this by increasing the `max_rounds` argument. """ resolution = Resolution(self.provider, self.reporter) resolution.resolve(requirements, max_rounds=max_rounds) return resolution.state
Remove the "extra == ..." operands from the list. This is not a comprehensive implementation, but relies on an important characteristic of metadata generation: The "extra == ..." operand is always associated with an "and" operator. This means that we can simply remove the operand and the "and" operator associated with it. def _strip_extra(elements): """Remove the "extra == ..." operands from the list. This is not a comprehensive implementation, but relies on an important characteristic of metadata generation: The "extra == ..." operand is always associated with an "and" operator. This means that we can simply remove the operand and the "and" operator associated with it. """ extra_indexes = [] for i, element in enumerate(elements): if isinstance(element, list): cancelled = _strip_extra(element) if cancelled: extra_indexes.append(i) elif isinstance(element, tuple) and element[0].value == "extra": extra_indexes.append(i) for i in reversed(extra_indexes): del elements[i] if i > 0 and elements[i - 1] == "and": # Remove the "and" before it. del elements[i - 1] elif elements: # This shouldn't ever happen, but is included for completeness. # If there is not an "and" before this element, try to remove the # operator after it. del elements[0] return (not elements)
Build a new marker without the `extra == ...` part. The implementation relies very deep into packaging's internals, but I don't have a better way now (except implementing the whole thing myself). This could return `None` if the `extra == ...` part is the only one in the input marker. def get_without_extra(marker): """Build a new marker without the `extra == ...` part. The implementation relies very deep into packaging's internals, but I don't have a better way now (except implementing the whole thing myself). This could return `None` if the `extra == ...` part is the only one in the input marker. """ # TODO: Why is this very deep in the internals? Why is a better solution # implementing it yourself when someone is already maintaining a codebase # for this? It's literally a grammar implementation that is required to # meet the demands of a pep... -d if not marker: return None marker = Marker(str(marker)) elements = marker._markers _strip_extra(elements) if elements: return marker return None
Collect "extra == ..." operands from a marker. Returns a list of str. Each str is a speficied extra in this marker. def get_contained_extras(marker): """Collect "extra == ..." operands from a marker. Returns a list of str. Each str is a speficied extra in this marker. """ if not marker: return set() marker = Marker(str(marker)) extras = set() _markers_collect_extras(marker._markers, extras) return extras
Check whehter a marker contains an "extra == ..." operand. def contains_extra(marker): """Check whehter a marker contains an "extra == ..." operand. """ if not marker: return False marker = Marker(str(marker)) return _markers_contains_extra(marker._markers)
Return any errors which have occurred. def get_errors(self): """ Return any errors which have occurred. """ result = [] while not self.errors.empty(): # pragma: no cover try: e = self.errors.get(False) result.append(e) except self.errors.Empty: continue self.errors.task_done() return result
For a given project, get a dictionary mapping available versions to Distribution instances. This calls _get_project to do all the work, and just implements a caching layer on top. def get_project(self, name): """ For a given project, get a dictionary mapping available versions to Distribution instances. This calls _get_project to do all the work, and just implements a caching layer on top. """ if self._cache is None: # pragma: no cover result = self._get_project(name) elif name in self._cache: result = self._cache[name] else: self.clear_errors() result = self._get_project(name) self._cache[name] = result return result
Give an url a score which can be used to choose preferred URLs for a given project release. def score_url(self, url): """ Give an url a score which can be used to choose preferred URLs for a given project release. """ t = urlparse(url) basename = posixpath.basename(t.path) compatible = True is_wheel = basename.endswith('.whl') is_downloadable = basename.endswith(self.downloadable_extensions) if is_wheel: compatible = is_compatible(Wheel(basename), self.wheel_tags) return (t.scheme == 'https', 'pypi.python.org' in t.netloc, is_downloadable, is_wheel, compatible, basename)
Choose one of two URLs where both are candidates for distribution archives for the same version of a distribution (for example, .tar.gz vs. zip). The current implementation favours https:// URLs over http://, archives from PyPI over those from other locations, wheel compatibility (if a wheel) and then the archive name. def prefer_url(self, url1, url2): """ Choose one of two URLs where both are candidates for distribution archives for the same version of a distribution (for example, .tar.gz vs. zip). The current implementation favours https:// URLs over http://, archives from PyPI over those from other locations, wheel compatibility (if a wheel) and then the archive name. """ result = url2 if url1: s1 = self.score_url(url1) s2 = self.score_url(url2) if s1 > s2: result = url1 if result != url2: logger.debug('Not replacing %r with %r', url1, url2) else: logger.debug('Replacing %r with %r', url1, url2) return result
Get a digest from a dictionary by looking at keys of the form 'algo_digest'. Returns a 2-tuple (algo, digest) if found, else None. Currently looks only for SHA256, then MD5. def _get_digest(self, info): """ Get a digest from a dictionary by looking at keys of the form 'algo_digest'. Returns a 2-tuple (algo, digest) if found, else None. Currently looks only for SHA256, then MD5. """ result = None for algo in ('sha256', 'md5'): key = '%s_digest' % algo if key in info: result = (algo, info[key]) break return result
Return the URLs of all the links on a page together with information about their "rel" attribute, for determining which ones to treat as downloads and which ones to queue for further scraping. def links(self): """ Return the URLs of all the links on a page together with information about their "rel" attribute, for determining which ones to treat as downloads and which ones to queue for further scraping. """ def clean(url): "Tidy up an URL." scheme, netloc, path, params, query, frag = urlparse(url) return urlunparse((scheme, netloc, quote(path), params, query, frag)) result = set() for match in self._href.finditer(self.data): d = match.groupdict('') rel = (d['rel1'] or d['rel2'] or d['rel3'] or d['rel4'] or d['rel5'] or d['rel6']) url = d['url1'] or d['url2'] or d['url3'] url = urljoin(self.base_url, url) url = unescape(url) url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url) result.add((url, rel)) # We sort the result, hoping to bring the most recent versions # to the front result = sorted(result, key=lambda t: t[0], reverse=True) return result
Threads are created only when get_project is called, and terminate before it returns. They are there primarily to parallelise I/O (i.e. fetching web pages). def _prepare_threads(self): """ Threads are created only when get_project is called, and terminate before it returns. They are there primarily to parallelise I/O (i.e. fetching web pages). """ self._threads = [] for i in range(self.num_workers): t = threading.Thread(target=self._fetch) t.setDaemon(True) t.start() self._threads.append(t)
Tell all the threads to terminate (by sending a sentinel value) and wait for them to do so. def _wait_threads(self): """ Tell all the threads to terminate (by sending a sentinel value) and wait for them to do so. """ # Note that you need two loops, since you can't say which # thread will get each sentinel for t in self._threads: self._to_fetch.put(None) # sentinel for t in self._threads: t.join() self._threads = []
See if an URL is a suitable download for a project. If it is, register information in the result dictionary (for _get_project) about the specific version it's for. Note that the return value isn't actually used other than as a boolean value. def _process_download(self, url): """ See if an URL is a suitable download for a project. If it is, register information in the result dictionary (for _get_project) about the specific version it's for. Note that the return value isn't actually used other than as a boolean value. """ if self.platform_check and self._is_platform_dependent(url): info = None else: info = self.convert_url_to_download_info(url, self.project_name) logger.debug('process_download: %s -> %s', url, info) if info: with self._lock: # needed because self.result is shared self._update_version_data(self.result, info) return info
Determine whether a link URL from a referring page and with a particular "rel" attribute should be queued for scraping. def _should_queue(self, link, referrer, rel): """ Determine whether a link URL from a referring page and with a particular "rel" attribute should be queued for scraping. """ scheme, netloc, path, _, _, _ = urlparse(link) if path.endswith(self.source_extensions + self.binary_extensions + self.excluded_extensions): result = False elif self.skip_externals and not link.startswith(self.base_url): result = False elif not referrer.startswith(self.base_url): result = False elif rel not in ('homepage', 'download'): result = False elif scheme not in ('http', 'https', 'ftp'): result = False elif self._is_platform_dependent(link): result = False else: host = netloc.split(':', 1)[0] if host.lower() == 'localhost': result = False else: result = True logger.debug('should_queue: %s (%s) from %s -> %s', link, rel, referrer, result) return result
Get a URL to fetch from the work queue, get the HTML page, examine its links for download candidates and candidates for further scraping. This is a handy method to run in a thread. def _fetch(self): """ Get a URL to fetch from the work queue, get the HTML page, examine its links for download candidates and candidates for further scraping. This is a handy method to run in a thread. """ while True: url = self._to_fetch.get() try: if url: page = self.get_page(url) if page is None: # e.g. after an error continue for link, rel in page.links: if link not in self._seen: try: self._seen.add(link) if (not self._process_download(link) and self._should_queue(link, url, rel)): logger.debug('Queueing %s from %s', link, url) self._to_fetch.put(link) except MetadataInvalidError: # e.g. invalid versions pass except Exception as e: # pragma: no cover self.errors.put(text_type(e)) finally: # always do this, to avoid hangs :-) self._to_fetch.task_done() if not url: #logger.debug('Sentinel seen, quitting.') break
Return all the distribution names known to this locator. def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() page = self.get_page(self.base_url) if not page: raise DistlibException('Unable to get %s' % self.base_url) for match in self._distname_re.finditer(page.data): result.add(match.group(1)) return result
Return all the distribution names known to this locator. def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() for root, dirs, files in os.walk(self.base_dir): for fn in files: if self.should_include(fn, root): fn = os.path.join(root, fn) url = urlunparse(('file', '', pathname2url(os.path.abspath(fn)), '', '', '')) info = self.convert_url_to_download_info(url, None) if info: result.add(info['name']) if not self.recursive: break return result
Return all the distribution names known to this locator. def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() for locator in self.locators: try: result |= locator.get_distribution_names() except NotImplementedError: pass return result
Add a distribution to the finder. This will update internal information about who provides what. :param dist: The distribution to add. def add_distribution(self, dist): """ Add a distribution to the finder. This will update internal information about who provides what. :param dist: The distribution to add. """ logger.debug('adding distribution %s', dist) name = dist.key self.dists_by_name[name] = dist self.dists[(name, dist.version)] = dist for p in dist.provides: name, version = parse_name_and_version(p) logger.debug('Add to provided: %s, %s, %s', name, version, dist) self.provided.setdefault(name, set()).add((version, dist))
Remove a distribution from the finder. This will update internal information about who provides what. :param dist: The distribution to remove. def remove_distribution(self, dist): """ Remove a distribution from the finder. This will update internal information about who provides what. :param dist: The distribution to remove. """ logger.debug('removing distribution %s', dist) name = dist.key del self.dists_by_name[name] del self.dists[(name, dist.version)] for p in dist.provides: name, version = parse_name_and_version(p) logger.debug('Remove from provided: %s, %s, %s', name, version, dist) s = self.provided[name] s.remove((version, dist)) if not s: del self.provided[name]
Get a version matcher for a requirement. :param reqt: The requirement :type reqt: str :return: A version matcher (an instance of :class:`distlib.version.Matcher`). def get_matcher(self, reqt): """ Get a version matcher for a requirement. :param reqt: The requirement :type reqt: str :return: A version matcher (an instance of :class:`distlib.version.Matcher`). """ try: matcher = self.scheme.matcher(reqt) except UnsupportedVersionError: # pragma: no cover # XXX compat-mode if cannot read the version name = reqt.split()[0] matcher = self.scheme.matcher(name) return matcher
Find the distributions which can fulfill a requirement. :param reqt: The requirement. :type reqt: str :return: A set of distribution which can fulfill the requirement. def find_providers(self, reqt): """ Find the distributions which can fulfill a requirement. :param reqt: The requirement. :type reqt: str :return: A set of distribution which can fulfill the requirement. """ matcher = self.get_matcher(reqt) name = matcher.key # case-insensitive result = set() provided = self.provided if name in provided: for version, provider in provided[name]: try: match = matcher.match(version) except UnsupportedVersionError: match = False if match: result.add(provider) break return result
Attempt to replace one provider with another. This is typically used when resolving dependencies from multiple sources, e.g. A requires (B >= 1.0) while C requires (B >= 1.1). For successful replacement, ``provider`` must meet all the requirements which ``other`` fulfills. :param provider: The provider we are trying to replace with. :param other: The provider we're trying to replace. :param problems: If False is returned, this will contain what problems prevented replacement. This is currently a tuple of the literal string 'cantreplace', ``provider``, ``other`` and the set of requirements that ``provider`` couldn't fulfill. :return: True if we can replace ``other`` with ``provider``, else False. def try_to_replace(self, provider, other, problems): """ Attempt to replace one provider with another. This is typically used when resolving dependencies from multiple sources, e.g. A requires (B >= 1.0) while C requires (B >= 1.1). For successful replacement, ``provider`` must meet all the requirements which ``other`` fulfills. :param provider: The provider we are trying to replace with. :param other: The provider we're trying to replace. :param problems: If False is returned, this will contain what problems prevented replacement. This is currently a tuple of the literal string 'cantreplace', ``provider``, ``other`` and the set of requirements that ``provider`` couldn't fulfill. :return: True if we can replace ``other`` with ``provider``, else False. """ rlist = self.reqts[other] unmatched = set() for s in rlist: matcher = self.get_matcher(s) if not matcher.match(provider.version): unmatched.add(s) if unmatched: # can't replace other with provider problems.add(('cantreplace', provider, other, frozenset(unmatched))) result = False else: # can replace other with provider self.remove_distribution(other) del self.reqts[other] for s in rlist: self.reqts.setdefault(provider, set()).add(s) self.add_distribution(provider) result = True return result
Find a distribution and all distributions it depends on. :param requirement: The requirement specifying the distribution to find, or a Distribution instance. :param meta_extras: A list of meta extras such as :test:, :build: and so on. :param prereleases: If ``True``, allow pre-release versions to be returned - otherwise, don't return prereleases unless they're all that's available. Return a set of :class:`Distribution` instances and a set of problems. The distributions returned should be such that they have the :attr:`required` attribute set to ``True`` if they were from the ``requirement`` passed to ``find()``, and they have the :attr:`build_time_dependency` attribute set to ``True`` unless they are post-installation dependencies of the ``requirement``. The problems should be a tuple consisting of the string ``'unsatisfied'`` and the requirement which couldn't be satisfied by any distribution known to the locator. def find(self, requirement, meta_extras=None, prereleases=False): """ Find a distribution and all distributions it depends on. :param requirement: The requirement specifying the distribution to find, or a Distribution instance. :param meta_extras: A list of meta extras such as :test:, :build: and so on. :param prereleases: If ``True``, allow pre-release versions to be returned - otherwise, don't return prereleases unless they're all that's available. Return a set of :class:`Distribution` instances and a set of problems. The distributions returned should be such that they have the :attr:`required` attribute set to ``True`` if they were from the ``requirement`` passed to ``find()``, and they have the :attr:`build_time_dependency` attribute set to ``True`` unless they are post-installation dependencies of the ``requirement``. The problems should be a tuple consisting of the string ``'unsatisfied'`` and the requirement which couldn't be satisfied by any distribution known to the locator. """ self.provided = {} self.dists = {} self.dists_by_name = {} self.reqts = {} meta_extras = set(meta_extras or []) if ':*:' in meta_extras: meta_extras.remove(':*:') # :meta: and :run: are implicitly included meta_extras |= set([':test:', ':build:', ':dev:']) if isinstance(requirement, Distribution): dist = odist = requirement logger.debug('passed %s as requirement', odist) else: dist = odist = self.locator.locate(requirement, prereleases=prereleases) if dist is None: raise DistlibException('Unable to locate %r' % requirement) logger.debug('located %s', odist) dist.requested = True problems = set() todo = set([dist]) install_dists = set([odist]) while todo: dist = todo.pop() name = dist.key # case-insensitive if name not in self.dists_by_name: self.add_distribution(dist) else: #import pdb; pdb.set_trace() other = self.dists_by_name[name] if other != dist: self.try_to_replace(dist, other, problems) ireqts = dist.run_requires | dist.meta_requires sreqts = dist.build_requires ereqts = set() if meta_extras and dist in install_dists: for key in ('test', 'build', 'dev'): e = ':%s:' % key if e in meta_extras: ereqts |= getattr(dist, '%s_requires' % key) all_reqts = ireqts | sreqts | ereqts for r in all_reqts: providers = self.find_providers(r) if not providers: logger.debug('No providers found for %r', r) provider = self.locator.locate(r, prereleases=prereleases) # If no provider is found and we didn't consider # prereleases, consider them now. if provider is None and not prereleases: provider = self.locator.locate(r, prereleases=True) if provider is None: logger.debug('Cannot satisfy %r', r) problems.add(('unsatisfied', r)) else: n, v = provider.key, provider.version if (n, v) not in self.dists: todo.add(provider) providers.add(provider) if r in ireqts and dist in install_dists: install_dists.add(provider) logger.debug('Adding %s to install_dists', provider.name_and_version) for p in providers: name = p.key if name not in self.dists_by_name: self.reqts.setdefault(p, set()).add(r) else: other = self.dists_by_name[name] if other != p: # see if other can be replaced by p self.try_to_replace(p, other, problems) dists = set(self.dists.values()) for dist in dists: dist.build_time_dependency = dist not in install_dists if dist.build_time_dependency: logger.debug('%s is a build-time dependency only.', dist.name_and_version) logger.debug('find done for %s', odist) return dists, problems
Run in a thread to move output from a pipe to a queue. def _read_incoming(self): """Run in a thread to move output from a pipe to a queue.""" fileno = self.proc.stdout.fileno() while 1: buf = b'' try: buf = os.read(fileno, 1024) except OSError as e: self._log(e, 'read') if not buf: # This indicates we have reached EOF self._read_queue.put(None) return self._read_queue.put(buf)
Send data to the subprocess' stdin. Returns the number of bytes written. def send(self, s): '''Send data to the subprocess' stdin. Returns the number of bytes written. ''' s = self._coerce_send_string(s) self._log(s, 'send') b = self._encoder.encode(s, final=False) if PY3: return self.proc.stdin.write(b) else: # On Python 2, .write() returns None, so we return the length of # bytes written ourselves. This assumes they all got written. self.proc.stdin.write(b) return len(b)
Wraps send(), sending string ``s`` to child process, with os.linesep automatically appended. Returns number of bytes written. def sendline(self, s=''): '''Wraps send(), sending string ``s`` to child process, with os.linesep automatically appended. Returns number of bytes written. ''' n = self.send(s) return n + self.send(self.linesep)
Wait for the subprocess to finish. Returns the exit code. def wait(self): '''Wait for the subprocess to finish. Returns the exit code. ''' status = self.proc.wait() if status >= 0: self.exitstatus = status self.signalstatus = None else: self.exitstatus = None self.signalstatus = -status self.terminated = True return status
Sends a Unix signal to the subprocess. Use constants from the :mod:`signal` module to specify which signal. def kill(self, sig): '''Sends a Unix signal to the subprocess. Use constants from the :mod:`signal` module to specify which signal. ''' if sys.platform == 'win32': if sig in [signal.SIGINT, signal.CTRL_C_EVENT]: sig = signal.CTRL_C_EVENT elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]: sig = signal.CTRL_BREAK_EVENT else: sig = signal.SIGTERM os.kill(self.proc.pid, sig)
Like `mkdir`, but does not raise an exception if the directory already exists. def mkdir_p(*args, **kwargs): """Like `mkdir`, but does not raise an exception if the directory already exists. """ try: return os.mkdir(*args, **kwargs) except OSError as exc: if exc.errno != errno.EEXIST: raise
Attach a regular expression pattern matcher to a custom type converter function. This annotates the type converter with the :attr:`pattern` attribute. EXAMPLE: >>> import parse >>> @parse.with_pattern(r"\d+") ... def parse_number(text): ... return int(text) is equivalent to: >>> def parse_number(text): ... return int(text) >>> parse_number.pattern = r"\d+" :param pattern: regular expression pattern (as text) :param regex_group_count: Indicates how many regex-groups are in pattern. :return: wrapped function def with_pattern(pattern, regex_group_count=None): """Attach a regular expression pattern matcher to a custom type converter function. This annotates the type converter with the :attr:`pattern` attribute. EXAMPLE: >>> import parse >>> @parse.with_pattern(r"\d+") ... def parse_number(text): ... return int(text) is equivalent to: >>> def parse_number(text): ... return int(text) >>> parse_number.pattern = r"\d+" :param pattern: regular expression pattern (as text) :param regex_group_count: Indicates how many regex-groups are in pattern. :return: wrapped function """ def decorator(func): func.pattern = pattern func.regex_group_count = regex_group_count return func return decorator
Convert a string to an integer. The string may start with a sign. It may be of a base other than 10. If may start with a base indicator, 0#nnnn, which we assume should override the specified base. It may also have other non-numeric characters that we can ignore. def int_convert(base): '''Convert a string to an integer. The string may start with a sign. It may be of a base other than 10. If may start with a base indicator, 0#nnnn, which we assume should override the specified base. It may also have other non-numeric characters that we can ignore. ''' CHARS = '0123456789abcdefghijklmnopqrstuvwxyz' def f(string, match, base=base): if string[0] == '-': sign = -1 else: sign = 1 if string[0] == '0' and len(string) > 2: if string[1] in 'bB': base = 2 elif string[1] in 'oO': base = 8 elif string[1] in 'xX': base = 16 else: # just go with the base specifed pass chars = CHARS[:base] string = re.sub('[^%s]' % chars, '', string.lower()) return sign * int(string, base) return f
Convert the incoming string containing some date / time info into a datetime instance. def date_convert(string, match, ymd=None, mdy=None, dmy=None, d_m_y=None, hms=None, am=None, tz=None, mm=None, dd=None): '''Convert the incoming string containing some date / time info into a datetime instance. ''' groups = match.groups() time_only = False if mm and dd: y=datetime.today().year m=groups[mm] d=groups[dd] elif ymd is not None: y, m, d = re.split(r'[-/\s]', groups[ymd]) elif mdy is not None: m, d, y = re.split(r'[-/\s]', groups[mdy]) elif dmy is not None: d, m, y = re.split(r'[-/\s]', groups[dmy]) elif d_m_y is not None: d, m, y = d_m_y d = groups[d] m = groups[m] y = groups[y] else: time_only = True H = M = S = u = 0 if hms is not None and groups[hms]: t = groups[hms].split(':') if len(t) == 2: H, M = t else: H, M, S = t if '.' in S: S, u = S.split('.') u = int(float('.' + u) * 1000000) S = int(S) H = int(H) M = int(M) if am is not None: am = groups[am] if am: am = am.strip() if am == 'AM' and H == 12: # correction for "12" hour functioning as "0" hour: 12:15 AM = 00:15 by 24 hr clock H -= 12 elif am == 'PM' and H == 12: # no correction needed: 12PM is midday, 12:00 by 24 hour clock pass elif am == 'PM': H += 12 if tz is not None: tz = groups[tz] if tz == 'Z': tz = FixedTzOffset(0, 'UTC') elif tz: tz = tz.strip() if tz.isupper(): # TODO use the awesome python TZ module? pass else: sign = tz[0] if ':' in tz: tzh, tzm = tz[1:].split(':') elif len(tz) == 4: # 'snnn' tzh, tzm = tz[1], tz[2:4] else: tzh, tzm = tz[1:3], tz[3:5] offset = int(tzm) + int(tzh) * 60 if sign == '-': offset = -offset tz = FixedTzOffset(offset, tz) if time_only: d = time(H, M, S, u, tzinfo=tz) else: y = int(y) if m.isdigit(): m = int(m) else: m = MONTHS_MAP[m] d = int(d) d = datetime(y, m, d, H, M, S, u, tzinfo=tz) return d
Pull apart the format [[fill]align][0][width][.precision][type] def extract_format(format, extra_types): '''Pull apart the format [[fill]align][0][width][.precision][type] ''' fill = align = None if format[0] in '<>=^': align = format[0] format = format[1:] elif len(format) > 1 and format[1] in '<>=^': fill = format[0] align = format[1] format = format[2:] zero = False if format and format[0] == '0': zero = True format = format[1:] width = '' while format: if not format[0].isdigit(): break width += format[0] format = format[1:] if format.startswith('.'): # Precision isn't needed but we need to capture it so that # the ValueError isn't raised. format = format[1:] # drop the '.' precision = '' while format: if not format[0].isdigit(): break precision += format[0] format = format[1:] # the rest is the type, if present type = format if type and type not in ALLOWED_TYPES and type not in extra_types: raise ValueError('format spec %r not recognised' % type) return locals()
Using "format" attempt to pull values from "string". The format must match the string contents exactly. If the value you're looking for is instead just a part of the string use search(). If ``evaluate_result`` is True the return value will be an Result instance with two attributes: .fixed - tuple of fixed-position values from the string .named - dict of named values from the string If ``evaluate_result`` is False the return value will be a Match instance with one method: .evaluate_result() - This will return a Result instance like you would get with ``evaluate_result`` set to True The default behaviour is to match strings case insensitively. You may match with case by specifying case_sensitive=True. If the format is invalid a ValueError will be raised. See the module documentation for the use of "extra_types". In the case there is no match parse() will return None. def parse(format, string, extra_types=None, evaluate_result=True, case_sensitive=False): '''Using "format" attempt to pull values from "string". The format must match the string contents exactly. If the value you're looking for is instead just a part of the string use search(). If ``evaluate_result`` is True the return value will be an Result instance with two attributes: .fixed - tuple of fixed-position values from the string .named - dict of named values from the string If ``evaluate_result`` is False the return value will be a Match instance with one method: .evaluate_result() - This will return a Result instance like you would get with ``evaluate_result`` set to True The default behaviour is to match strings case insensitively. You may match with case by specifying case_sensitive=True. If the format is invalid a ValueError will be raised. See the module documentation for the use of "extra_types". In the case there is no match parse() will return None. ''' p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive) return p.parse(string, evaluate_result=evaluate_result)
Search "string" for the first occurrence of "format". The format may occur anywhere within the string. If instead you wish for the format to exactly match the string use parse(). Optionally start the search at "pos" character index and limit the search to a maximum index of endpos - equivalent to search(string[:endpos]). If ``evaluate_result`` is True the return value will be an Result instance with two attributes: .fixed - tuple of fixed-position values from the string .named - dict of named values from the string If ``evaluate_result`` is False the return value will be a Match instance with one method: .evaluate_result() - This will return a Result instance like you would get with ``evaluate_result`` set to True The default behaviour is to match strings case insensitively. You may match with case by specifying case_sensitive=True. If the format is invalid a ValueError will be raised. See the module documentation for the use of "extra_types". In the case there is no match parse() will return None. def search(format, string, pos=0, endpos=None, extra_types=None, evaluate_result=True, case_sensitive=False): '''Search "string" for the first occurrence of "format". The format may occur anywhere within the string. If instead you wish for the format to exactly match the string use parse(). Optionally start the search at "pos" character index and limit the search to a maximum index of endpos - equivalent to search(string[:endpos]). If ``evaluate_result`` is True the return value will be an Result instance with two attributes: .fixed - tuple of fixed-position values from the string .named - dict of named values from the string If ``evaluate_result`` is False the return value will be a Match instance with one method: .evaluate_result() - This will return a Result instance like you would get with ``evaluate_result`` set to True The default behaviour is to match strings case insensitively. You may match with case by specifying case_sensitive=True. If the format is invalid a ValueError will be raised. See the module documentation for the use of "extra_types". In the case there is no match parse() will return None. ''' p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive) return p.search(string, pos, endpos, evaluate_result=evaluate_result)
Match my format to the string exactly. Return a Result or Match instance or None if there's no match. def parse(self, string, evaluate_result=True): '''Match my format to the string exactly. Return a Result or Match instance or None if there's no match. ''' m = self._match_re.match(string) if m is None: return None if evaluate_result: return self.evaluate_result(m) else: return Match(self, m)
Search the string for my format. Optionally start the search at "pos" character index and limit the search to a maximum index of endpos - equivalent to search(string[:endpos]). If the ``evaluate_result`` argument is set to ``False`` a Match instance is returned instead of the actual Result instance. Return either a Result instance or None if there's no match. def search(self, string, pos=0, endpos=None, evaluate_result=True): '''Search the string for my format. Optionally start the search at "pos" character index and limit the search to a maximum index of endpos - equivalent to search(string[:endpos]). If the ``evaluate_result`` argument is set to ``False`` a Match instance is returned instead of the actual Result instance. Return either a Result instance or None if there's no match. ''' if endpos is None: endpos = len(string) m = self._search_re.search(string, pos, endpos) if m is None: return None if evaluate_result: return self.evaluate_result(m) else: return Match(self, m)
Search "string" for all occurrences of "format". Optionally start the search at "pos" character index and limit the search to a maximum index of endpos - equivalent to search(string[:endpos]). Returns an iterator that holds Result or Match instances for each format match found. def findall(self, string, pos=0, endpos=None, extra_types=None, evaluate_result=True): '''Search "string" for all occurrences of "format". Optionally start the search at "pos" character index and limit the search to a maximum index of endpos - equivalent to search(string[:endpos]). Returns an iterator that holds Result or Match instances for each format match found. ''' if endpos is None: endpos = len(string) return ResultIterator(self, string, pos, endpos, evaluate_result=evaluate_result)
Generate a Result instance for the given regex match object def evaluate_result(self, m): '''Generate a Result instance for the given regex match object''' # ok, figure the fixed fields we've pulled out and type convert them fixed_fields = list(m.groups()) for n in self._fixed_fields: if n in self._type_conversions: fixed_fields[n] = self._type_conversions[n](fixed_fields[n], m) fixed_fields = tuple(fixed_fields[n] for n in self._fixed_fields) # grab the named fields, converting where requested groupdict = m.groupdict() named_fields = {} name_map = {} for k in self._named_fields: korig = self._group_to_name_map[k] name_map[korig] = k if k in self._type_conversions: value = self._type_conversions[k](groupdict[k], m) else: value = groupdict[k] named_fields[korig] = value # now figure the match spans spans = dict((n, m.span(name_map[n])) for n in named_fields) spans.update((i, m.span(n + 1)) for i, n in enumerate(self._fixed_fields)) # and that's our result return Result(fixed_fields, self._expand_named_fields(named_fields), spans)
Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile. def install( ctx, state, **kwargs ): """Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile.""" from ..core import do_install retcode = do_install( dev=state.installstate.dev, three=state.three, python=state.python, pypi_mirror=state.pypi_mirror, system=state.system, lock=not state.installstate.skip_lock, ignore_pipfile=state.installstate.ignore_pipfile, skip_lock=state.installstate.skip_lock, requirements=state.installstate.requirementstxt, sequential=state.installstate.sequential, pre=state.installstate.pre, code=state.installstate.code, deploy=state.installstate.deploy, keep_outdated=state.installstate.keep_outdated, selective_upgrade=state.installstate.selective_upgrade, index_url=state.index, extra_index_url=state.extra_index_urls, packages=state.installstate.packages, editable_packages=state.installstate.editables, ) if retcode: ctx.abort()
Un-installs a provided package and removes it from Pipfile. def uninstall( ctx, state, all_dev=False, all=False, **kwargs ): """Un-installs a provided package and removes it from Pipfile.""" from ..core import do_uninstall retcode = do_uninstall( packages=state.installstate.packages, editable_packages=state.installstate.editables, three=state.three, python=state.python, system=state.system, lock=not state.installstate.skip_lock, all_dev=all_dev, all=all, keep_outdated=state.installstate.keep_outdated, pypi_mirror=state.pypi_mirror, ctx=ctx ) if retcode: sys.exit(retcode)
Generates Pipfile.lock. def lock( ctx, state, **kwargs ): """Generates Pipfile.lock.""" from ..core import ensure_project, do_init, do_lock # Ensure that virtualenv is available. ensure_project(three=state.three, python=state.python, pypi_mirror=state.pypi_mirror) if state.installstate.requirementstxt: do_init( dev=state.installstate.dev, requirements=state.installstate.requirementstxt, pypi_mirror=state.pypi_mirror, pre=state.installstate.pre, ) do_lock( ctx=ctx, clear=state.clear, pre=state.installstate.pre, keep_outdated=state.installstate.keep_outdated, pypi_mirror=state.pypi_mirror, )
Spawns a shell within the virtualenv. def shell( state, fancy=False, shell_args=None, anyway=False, ): """Spawns a shell within the virtualenv.""" from ..core import load_dot_env, do_shell # Prevent user from activating nested environments. if "PIPENV_ACTIVE" in os.environ: # If PIPENV_ACTIVE is set, VIRTUAL_ENV should always be set too. venv_name = os.environ.get("VIRTUAL_ENV", "UNKNOWN_VIRTUAL_ENVIRONMENT") if not anyway: echo( "{0} {1} {2}\nNo action taken to avoid nested environments.".format( crayons.normal("Shell for"), crayons.green(venv_name, bold=True), crayons.normal("already activated.", bold=True), ), err=True, ) sys.exit(1) # Load .env file. load_dot_env() # Use fancy mode for Windows. if os.name == "nt": fancy = True do_shell( three=state.three, python=state.python, fancy=fancy, shell_args=shell_args, pypi_mirror=state.pypi_mirror, )
Spawns a command installed into the virtualenv. def run(state, command, args): """Spawns a command installed into the virtualenv.""" from ..core import do_run do_run( command=command, args=args, three=state.three, python=state.python, pypi_mirror=state.pypi_mirror )
Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile. def check( state, unused=False, style=False, ignore=None, args=None, **kwargs ): """Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile.""" from ..core import do_check do_check( three=state.three, python=state.python, system=state.system, unused=unused, ignore=ignore, args=args, pypi_mirror=state.pypi_mirror, )
Runs lock, then sync. def update( ctx, state, bare=False, dry_run=None, outdated=False, **kwargs ): """Runs lock, then sync.""" from ..core import ( ensure_project, do_outdated, do_lock, do_sync, project, ) ensure_project(three=state.three, python=state.python, warn=True, pypi_mirror=state.pypi_mirror) if not outdated: outdated = bool(dry_run) if outdated: do_outdated(pypi_mirror=state.pypi_mirror) packages = [p for p in state.installstate.packages if p] editable = [p for p in state.installstate.editables if p] if not packages: echo( "{0} {1} {2} {3}{4}".format( crayons.white("Running", bold=True), crayons.red("$ pipenv lock", bold=True), crayons.white("then", bold=True), crayons.red("$ pipenv sync", bold=True), crayons.white(".", bold=True), ) ) else: for package in packages + editable: if package not in project.all_packages: echo( "{0}: {1} was not found in your Pipfile! Aborting." "".format( crayons.red("Warning", bold=True), crayons.green(package, bold=True), ), err=True, ) ctx.abort() do_lock( clear=state.clear, pre=state.installstate.pre, keep_outdated=state.installstate.keep_outdated, pypi_mirror=state.pypi_mirror, ) do_sync( ctx=ctx, dev=state.installstate.dev, three=state.three, python=state.python, bare=bare, dont_upgrade=not state.installstate.keep_outdated, user=False, clear=state.clear, unused=False, sequential=state.installstate.sequential, pypi_mirror=state.pypi_mirror, )
Displays currently-installed dependency graph information. def graph(bare=False, json=False, json_tree=False, reverse=False): """Displays currently-installed dependency graph information.""" from ..core import do_graph do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse)
View a given module in your editor. This uses the EDITOR environment variable. You can temporarily override it, for example: EDITOR=atom pipenv open requests def run_open(state, module, *args, **kwargs): """View a given module in your editor. This uses the EDITOR environment variable. You can temporarily override it, for example: EDITOR=atom pipenv open requests """ from ..core import which, ensure_project, inline_activate_virtual_environment # Ensure that virtualenv is available. ensure_project( three=state.three, python=state.python, validate=False, pypi_mirror=state.pypi_mirror, ) c = delegator.run( '{0} -c "import {1}; print({1}.__file__);"'.format(which("python"), module) ) try: assert c.return_code == 0 except AssertionError: echo(crayons.red("Module not found!")) sys.exit(1) if "__init__.py" in c.out: p = os.path.dirname(c.out.strip().rstrip("cdo")) else: p = c.out.strip().rstrip("cdo") echo(crayons.normal("Opening {0!r} in your EDITOR.".format(p), bold=True)) inline_activate_virtual_environment() edit(filename=p) return 0
Installs all packages specified in Pipfile.lock. def sync( ctx, state, bare=False, user=False, unused=False, **kwargs ): """Installs all packages specified in Pipfile.lock.""" from ..core import do_sync retcode = do_sync( ctx=ctx, dev=state.installstate.dev, three=state.three, python=state.python, bare=bare, dont_upgrade=(not state.installstate.keep_outdated), user=user, clear=state.clear, unused=unused, sequential=state.installstate.sequential, pypi_mirror=state.pypi_mirror, ) if retcode: ctx.abort()
Uninstalls all packages not specified in Pipfile.lock. def clean(ctx, state, dry_run=False, bare=False, user=False): """Uninstalls all packages not specified in Pipfile.lock.""" from ..core import do_clean do_clean(ctx=ctx, three=state.three, python=state.python, dry_run=dry_run, system=state.system)
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): """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. """ allowed = digits radix = 10 if isHex: allowed = hexDigits radix = 16 charStack = [] # Consume all the characters that are in range while making sure we # don't hit an EOF. c = self.stream.char() while c in allowed and c is not EOF: charStack.append(c) c = self.stream.char() # Convert the set of characters consumed to an int. charAsInt = int("".join(charStack), radix) # Certain characters get replaced with others if charAsInt in replacementCharacters: char = replacementCharacters[charAsInt] self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) elif ((0xD800 <= charAsInt <= 0xDFFF) or (charAsInt > 0x10FFFF)): char = "\uFFFD" self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) else: # Should speed up this check somehow (e.g. move the set to a constant) if ((0x0001 <= charAsInt <= 0x0008) or (0x000E <= charAsInt <= 0x001F) or (0x007F <= charAsInt <= 0x009F) or (0xFDD0 <= charAsInt <= 0xFDEF) or charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF])): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) try: # Try/except needed as UCS-2 Python builds' unichar only works # within the BMP. char = chr(charAsInt) except ValueError: v = charAsInt - 0x10000 char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF)) # Discard the ; if present. Otherwise, put it back on the queue and # invoke parseError on parser. if c != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "numeric-entity-without-semicolon"}) self.stream.unget(c) return char
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): """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. """ token = self.currentToken # Add token to the queue to be yielded if (token["type"] in tagTokenTypes): token["name"] = token["name"].translate(asciiUpper2Lower) if token["type"] == tokenTypes["EndTag"]: if token["data"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "attributes-in-end-tag"}) if token["selfClosing"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "self-closing-flag-on-end-tag"}) self.tokenQueue.append(token) self.state = self.dataState
Converts a list of distributions into a PackageSet. def create_package_set_from_installed(**kwargs): # type: (**Any) -> Tuple[PackageSet, bool] """Converts a list of distributions into a PackageSet. """ # Default to using all packages installed on the system if kwargs == {}: kwargs = {"local_only": False, "skip": ()} package_set = {} problems = False for dist in get_installed_distributions(**kwargs): name = canonicalize_name(dist.project_name) try: package_set[name] = PackageDetails(dist.version, dist.requires()) except RequirementParseError as e: # Don't crash on broken metadata logging.warning("Error parsing requirements for %s: %s", name, e) problems = True return package_set, problems
Check if a package set is consistent If should_ignore is passed, it should be a callable that takes a package name and returns a boolean. def check_package_set(package_set, should_ignore=None): # type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult """Check if a package set is consistent If should_ignore is passed, it should be a callable that takes a package name and returns a boolean. """ if should_ignore is None: def should_ignore(name): return False missing = dict() conflicting = dict() for package_name in package_set: # Info about dependencies of package_name missing_deps = set() # type: Set[Missing] conflicting_deps = set() # type: Set[Conflicting] if should_ignore(package_name): continue for req in package_set[package_name].requires: name = canonicalize_name(req.project_name) # type: str # Check if it's missing if name not in package_set: missed = True if req.marker is not None: missed = req.marker.evaluate() if missed: missing_deps.add((name, req)) continue # Check if there's a conflict version = package_set[name].version # type: str if not req.specifier.contains(version, prereleases=True): conflicting_deps.add((name, version, req)) if missing_deps: missing[package_name] = sorted(missing_deps, key=str) if conflicting_deps: conflicting[package_name] = sorted(conflicting_deps, key=str) return missing, conflicting
For checking if the dependency graph would be consistent after \ installing given requirements def check_install_conflicts(to_install): # type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult] """For checking if the dependency graph would be consistent after \ installing given requirements """ # Start from the current state package_set, _ = create_package_set_from_installed() # Install packages would_be_installed = _simulate_installation_of(to_install, package_set) # Only warn about directly-dependent packages; create a whitelist of them whitelist = _create_whitelist(would_be_installed, package_set) return ( package_set, check_package_set( package_set, should_ignore=lambda name: name not in whitelist ) )
Computes the version of packages after installing to_install. def _simulate_installation_of(to_install, package_set): # type: (List[InstallRequirement], PackageSet) -> Set[str] """Computes the version of packages after installing to_install. """ # Keep track of packages that were installed installed = set() # Modify it as installing requirement_set would (assuming no errors) for inst_req in to_install: dist = make_abstract_dist(inst_req).dist() name = canonicalize_name(dist.key) package_set[name] = PackageDetails(dist.version, dist.requires()) installed.add(name) return installed
We define three types of bytes: alphabet: english alphabets [a-zA-Z] international: international characters [\x80-\xFF] marker: everything else [^a-zA-Z\x80-\xFF] The input buffer can be thought to contain a series of words delimited by markers. This function works to filter all words that contain at least one international character. All contiguous sequences of markers are replaced by a single space ascii character. This filter applies to all scripts which do not use English characters. def filter_international_words(buf): """ We define three types of bytes: alphabet: english alphabets [a-zA-Z] international: international characters [\x80-\xFF] marker: everything else [^a-zA-Z\x80-\xFF] The input buffer can be thought to contain a series of words delimited by markers. This function works to filter all words that contain at least one international character. All contiguous sequences of markers are replaced by a single space ascii character. This filter applies to all scripts which do not use English characters. """ filtered = bytearray() # This regex expression filters out only words that have at-least one # international character. The word may include one marker character at # the end. words = re.findall(b'[a-zA-Z]*[\x80-\xFF]+[a-zA-Z]*[^a-zA-Z\x80-\xFF]?', buf) for word in words: filtered.extend(word[:-1]) # If the last character in the word is a marker, replace it with a # space as markers shouldn't affect our analysis (they are used # similarly across all languages and may thus have similar # frequencies). last_char = word[-1:] if not last_char.isalpha() and last_char < b'\x80': last_char = b' ' filtered.extend(last_char) return filtered
Returns a copy of ``buf`` that retains only the sequences of English alphabet and high byte characters that are not between <> characters. Also retains English alphabet and high byte characters immediately before occurrences of >. This filter can be applied to all scripts which contain both English characters and extended ASCII characters, but is currently only used by ``Latin1Prober``. def filter_with_english_letters(buf): """ Returns a copy of ``buf`` that retains only the sequences of English alphabet and high byte characters that are not between <> characters. Also retains English alphabet and high byte characters immediately before occurrences of >. This filter can be applied to all scripts which contain both English characters and extended ASCII characters, but is currently only used by ``Latin1Prober``. """ filtered = bytearray() in_tag = False prev = 0 for curr in range(len(buf)): # Slice here to get bytes instead of an int with Python 3 buf_char = buf[curr:curr + 1] # Check if we're coming out of or entering an HTML tag if buf_char == b'>': in_tag = False elif buf_char == b'<': in_tag = True # If current character is not extended-ASCII and not alphabetic... if buf_char < b'\x80' and not buf_char.isalpha(): # ...and we're not in a tag if curr > prev and not in_tag: # Keep everything after last non-extended-ASCII, # non-alphabetic character filtered.extend(buf[prev:curr]) # Output a space to delimit stretch we kept filtered.extend(b' ') prev = curr + 1 # If we're not in a tag... if not in_tag: # Keep everything after last non-extended-ASCII, non-alphabetic # character filtered.extend(buf[prev:]) return filtered
Join the two paths represented by the respective (drive, root, parts) tuples. Return a new (drive, root, parts) tuple. def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2): """ Join the two paths represented by the respective (drive, root, parts) tuples. Return a new (drive, root, parts) tuple. """ if root2: if not drv2 and drv: return drv, root2, [drv + root2] + parts2[1:] elif drv2: if drv2 == drv or self.casefold(drv2) == self.casefold(drv): # Same drive => second path is relative to the first return drv, root, parts + parts2[1:] else: # Second path is non-anchored (common case) return drv, root, parts + parts2 return drv2, root2, parts2
Iterate over all child paths of `parent_path` matched by this selector. This can contain parent_path itself. def select_from(self, parent_path): """Iterate over all child paths of `parent_path` matched by this selector. This can contain parent_path itself.""" path_cls = type(parent_path) is_dir = path_cls.is_dir exists = path_cls.exists scandir = parent_path._accessor.scandir if not is_dir(parent_path): return iter([]) return self._select_from(parent_path, is_dir, exists, scandir)
Return the string representation of the path with forward (/) slashes. def as_posix(self): """Return the string representation of the path with forward (/) slashes.""" f = self._flavour return str(self).replace(f.sep, '/')
The final path component, if any. def name(self): """The final path component, if any.""" parts = self._parts if len(parts) == (1 if (self._drv or self._root) else 0): return '' return parts[-1]
The final component's last suffix, if any. def suffix(self): """The final component's last suffix, if any.""" name = self.name i = name.rfind('.') if 0 < i < len(name) - 1: return name[i:] else: return ''
A list of the final component's suffixes, if any. def suffixes(self): """A list of the final component's suffixes, if any.""" name = self.name if name.endswith('.'): return [] name = name.lstrip('.') return ['.' + suffix for suffix in name.split('.')[1:]]
The final path component, minus its last suffix. def stem(self): """The final path component, minus its last suffix.""" name = self.name i = name.rfind('.') if 0 < i < len(name) - 1: return name[:i] else: return name
Return a new path with the file name changed. def with_name(self, name): """Return a new path with the file name changed.""" if not self.name: raise ValueError("%r has an empty name" % (self,)) drv, root, parts = self._flavour.parse_parts((name,)) if (not name or name[-1] in [self._flavour.sep, self._flavour.altsep] or drv or root or len(parts) != 1): raise ValueError("Invalid name %r" % (name)) return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
Return a new path with the file suffix changed (or added, if none). def with_suffix(self, suffix): """Return a new path with the file suffix changed (or added, if none). """ # XXX if suffix is None, should the current suffix be removed? f = self._flavour if f.sep in suffix or f.altsep and f.altsep in suffix: raise ValueError("Invalid suffix %r" % (suffix)) if suffix and not suffix.startswith('.') or suffix == '.': raise ValueError("Invalid suffix %r" % (suffix)) name = self.name if not name: raise ValueError("%r has an empty name" % (self,)) old_suffix = self.suffix if not old_suffix: name = name + suffix else: name = name[:-len(old_suffix)] + suffix return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
An object providing sequence-like access to the components in the filesystem path. def parts(self): """An object providing sequence-like access to the components in the filesystem path.""" # We cache the tuple to avoid building a new one each time .parts # is accessed. XXX is this necessary? try: return self._pparts except AttributeError: self._pparts = tuple(self._parts) return self._pparts
The logical parent of the path. def parent(self): """The logical parent of the path.""" drv = self._drv root = self._root parts = self._parts if len(parts) == 1 and (drv or root): return self return self._from_parsed_parts(drv, root, parts[:-1])
True if the path is absolute (has both a root and, if applicable, a drive). def is_absolute(self): """True if the path is absolute (has both a root and, if applicable, a drive).""" if not self._root: return False return not self._flavour.has_drv or bool(self._drv)
Return True if this path matches the given pattern. def match(self, path_pattern): """ Return True if this path matches the given pattern. """ cf = self._flavour.casefold path_pattern = cf(path_pattern) drv, root, pat_parts = self._flavour.parse_parts((path_pattern,)) if not pat_parts: raise ValueError("empty pattern") if drv and drv != cf(self._drv): return False if root and root != cf(self._root): return False parts = self._cparts if drv or root: if len(pat_parts) != len(parts): return False pat_parts = pat_parts[1:] elif len(pat_parts) > len(parts): return False for part, pat in zip(reversed(parts), reversed(pat_parts)): if not fnmatch.fnmatchcase(part, pat): return False return True
Open the file pointed by this path and return a file descriptor, as os.open() does. def _raw_open(self, flags, mode=0o777): """ Open the file pointed by this path and return a file descriptor, as os.open() does. """ if self._closed: self._raise_closed() return self._accessor.open(self, flags, mode)
Return whether other_path is the same or not as this file (as returned by os.path.samefile()). def samefile(self, other_path): """Return whether other_path is the same or not as this file (as returned by os.path.samefile()). """ if hasattr(os.path, "samestat"): st = self.stat() try: other_st = other_path.stat() except AttributeError: other_st = os.stat(other_path) return os.path.samestat(st, other_st) else: filename1 = six.text_type(self) filename2 = six.text_type(other_path) st1 = _win32_get_unique_path_id(filename1) st2 = _win32_get_unique_path_id(filename2) return st1 == st2
Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'. def iterdir(self): """Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'. """ if self._closed: self._raise_closed() for name in self._accessor.listdir(self): if name in ('.', '..'): # Yielding a path object for these makes little sense continue yield self._make_child_relpath(name) if self._closed: self._raise_closed()
Create this file with the given access mode, if it doesn't exist. def touch(self, mode=0o666, exist_ok=True): """ Create this file with the given access mode, if it doesn't exist. """ if self._closed: self._raise_closed() if exist_ok: # First try to bump modification time # Implementation note: GNU touch uses the UTIME_NOW option of # the utimensat() / futimens() functions. try: self._accessor.utime(self, None) except OSError: # Avoid exception chaining pass else: return flags = os.O_CREAT | os.O_WRONLY if not exist_ok: flags |= os.O_EXCL fd = self._raw_open(flags, mode) os.close(fd)
Create a new directory at this given path. def mkdir(self, mode=0o777, parents=False, exist_ok=False): """ Create a new directory at this given path. """ if self._closed: self._raise_closed() def _try_func(): self._accessor.mkdir(self, mode) def _exc_func(exc): if not parents or self.parent == self: raise exc self.parent.mkdir(parents=True, exist_ok=True) self.mkdir(mode, parents=False, exist_ok=exist_ok) try: _try_except_filenotfounderror(_try_func, _exc_func) except OSError: if not exist_ok or not self.is_dir(): raise
Change the permissions of the path, like os.chmod(). def chmod(self, mode): """ Change the permissions of the path, like os.chmod(). """ if self._closed: self._raise_closed() self._accessor.chmod(self, mode)
Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather than its target's. def lchmod(self, mode): """ Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather than its target's. """ if self._closed: self._raise_closed() self._accessor.lchmod(self, mode)
Remove this file or link. If the path is a directory, use rmdir() instead. def unlink(self): """ Remove this file or link. If the path is a directory, use rmdir() instead. """ if self._closed: self._raise_closed() self._accessor.unlink(self)
Remove this directory. The directory must be empty. def rmdir(self): """ Remove this directory. The directory must be empty. """ if self._closed: self._raise_closed() self._accessor.rmdir(self)
Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's. def lstat(self): """ Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's. """ if self._closed: self._raise_closed() return self._accessor.lstat(self)