INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create a standalone, in-memory repository. Using this function bypasses the `package_repository_manager` singleton. This is usually desired however, since in-memory repositories are for temporarily storing programmatically created packages, which we do not want to cache and that do not ...
def create_repository(cls, repository_data): """Create a standalone, in-memory repository. Using this function bypasses the `package_repository_manager` singleton. This is usually desired however, since in-memory repositories are for temporarily storing programmatically created packages...
Detect the best version depending on the fields used.
def _best_version(fields): """Detect the best version depending on the fields used.""" def _has_marker(keys, markers): for marker in markers: if marker in keys: return True return False keys = [] for key, value in fields.items(): if value in ([], 'UNK...
Read the metadata values from a file object.
def read_file(self, fileob): """Read the metadata values from a file object.""" msg = message_from_file(fileob) self._fields['Metadata-Version'] = msg['metadata-version'] # When reading, get all the fields we can for field in _ALL_FIELDS: if field not in msg: ...
Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided
def check(self, strict=False): """Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided""" self.set_metadata_version() # XXX should check the versions (if the file was loaded) missing, warnings = [], [] for attr in ('Name', ...
Create a widget containing an aligned set of widgets. Args: widgets (list of `QWidget`). horizontal (bool). align (str): One of: - 'left', 'right' (horizontal); - 'top', 'bottom' (vertical) parent_widget (`QWidget`): Owner widget, QWidget is created if this ...
def create_pane(widgets, horizontal, parent_widget=None, compact=False, compact_spacing=2): """Create a widget containing an aligned set of widgets. Args: widgets (list of `QWidget`). horizontal (bool). align (str): One of: - 'left', 'right' (horizontal); ...
Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon` is True
def get_icon(name, as_qicon=False): """Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon` is True""" filename = name + ".png" icon = icons.get(filename) if not icon: path = os.path.dirname(__file__) path = os.path.join(path, "icons") filepath = os.path.j...
Interpolate between two colors. Returns: `QColor` object.
def interp_color(a, b, f): """Interpolate between two colors. Returns: `QColor` object. """ a_ = (a.redF(), a.greenF(), a.blueF()) b_ = (b.redF(), b.greenF(), b.blueF()) a_ = [x * (1 - f) for x in a_] b_ = [x * f for x in b_] c = [x + y for x, y in zip(a_, b_)] return QtGui....
Create a toolbutton. Args: entries: List of (label, slot) tuples. Returns: `QtGui.QToolBar`.
def create_toolbutton(entries, parent=None): """Create a toolbutton. Args: entries: List of (label, slot) tuples. Returns: `QtGui.QToolBar`. """ btn = QtGui.QToolButton(parent) menu = QtGui.QMenu() actions = [] for label, slot in entries: action = add_menu_acti...
Return all distribution names known by an index. :param url: The URL of the index. :return: A list of all known distribution names.
def get_all_distribution_names(url=None): """ Return all distribution names known by an index. :param url: The URL of the index. :return: A list of all known distribution names. """ if url is None: url = DEFAULT_INDEX client = ServerProxy(url, timeout=3.0) return client.list_pack...
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) return (t.scheme != 'https', 'pypi.python.org' in t.netloc, posixpath.basename(t.path))
Update a result dictionary (the final result from _get_project) with a dictionary for a specific version, whih typically holds information gleaned from a filename or URL for an archive for the distribution.
def _update_version_data(self, result, info): """ Update a result dictionary (the final result from _get_project) with a dictionary for a specific version, whih typically holds information gleaned from a filename or URL for an archive for the distribution. """ name = info...
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() t...
Get the HTML for an URL, possibly from an in-memory cache. XXX TODO Note: this cache is never actually cleared. It's assumed that the data won't get stale over the lifetime of a locator instance (not necessarily true for the default_locator).
def get_page(self, url): """ Get the HTML for an URL, possibly from an in-memory cache. XXX TODO Note: this cache is never actually cleared. It's assumed that the data won't get stale over the lifetime of a locator instance (not necessarily true for the default_locator). ...
Find packages that depend on the given package. This is a reverse dependency lookup. A tree is constructed, showing what packages depend on the given package, with an optional depth limit. A resolve does not occur. Only the latest version of each package is used, and requirements from all variants of t...
def get_reverse_dependency_tree(package_name, depth=None, paths=None, build_requires=False, private_build_requires=False): """Find packages that depend on the given package. This is a reverse dependency lookup. A tree is constructed, showing what ...
Find packages that are plugins of the given package. Args: package_name (str): Name of the package. paths (list of str): Paths to search for packages, defaults to `config.packages_path`. Returns: list of str: The packages that are plugins of the given package.
def get_plugins(package_name, paths=None): """Find packages that are plugins of the given package. Args: package_name (str): Name of the package. paths (list of str): Paths to search for packages, defaults to `config.packages_path`. Returns: list of str: The packages th...
Search for resources. Args: resources_request (str): Resource to search, glob-style patterns are supported. If None, returns all matching resource types. Returns: 2-tuple: - str: resource type (family, package, variant); - List of `Resour...
def search(self, resources_request=None): """Search for resources. Args: resources_request (str): Resource to search, glob-style patterns are supported. If None, returns all matching resource types. Returns: 2-tuple: - str: resource type (fam...
Print formatted search results. Args: search_results (list of `ResourceSearchResult`): Search to format.
def print_search_results(self, search_results, buf=sys.stdout): """Print formatted search results. Args: search_results (list of `ResourceSearchResult`): Search to format. """ formatted_lines = self.format_search_results(search_results) pr = Printer(buf) for...
Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in.
def format_search_results(self, search_results): """Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in. """ formatted_lines = [] for search_result ...
Read a graph from a string in Dot language and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in Dot format specifying a graph. @rtype: graph @return: Graph
def read(string): """ Read a graph from a string in Dot language and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in Dot format specifying a graph. @rtype: graph @return: Graph """ ...
Return a string specifying the given graph in Dot language. @type G: graph @param G: Graph. @type weighted: boolean @param weighted: Whether edges should be labelled with their weight. @rtype: string @return: String specifying the graph in Dot Language.
def write(G, weighted=False): """ Return a string specifying the given graph in Dot language. @type G: graph @param G: Graph. @type weighted: boolean @param weighted: Whether edges should be labelled with their weight. @rtype: string @return: String specifying the graph in ...
Read a hypergraph from a string in dot format. Nodes and edges specified in the input will be added to the current hypergraph. @type string: string @param string: Input string in dot format specifying a graph. @rtype: hypergraph @return: Hypergraph
def read_hypergraph(string): """ Read a hypergraph from a string in dot format. Nodes and edges specified in the input will be added to the current hypergraph. @type string: string @param string: Input string in dot format specifying a graph. @rtype: hypergraph @return: Hypergrap...
Return a string specifying the given hypergraph in DOT Language. @type hgr: hypergraph @param hgr: Hypergraph. @type colored: boolean @param colored: Whether hyperedges should be colored. @rtype: string @return: String specifying the hypergraph in DOT Language.
def write_hypergraph(hgr, colored = False): """ Return a string specifying the given hypergraph in DOT Language. @type hgr: hypergraph @param hgr: Hypergraph. @type colored: boolean @param colored: Whether hyperedges should be colored. @rtype: string @return: String specify...
Checks whether a string is a dot language ID. It will check whether the string is solely composed by the characters allowed in an ID or not. If the string is one of the reserved keywords it will need quotes too but the user will need to add them manually.
def needs_quotes( s ): """Checks whether a string is a dot language ID. It will check whether the string is solely composed by the characters allowed in an ID or not. If the string is one of the reserved keywords it will need quotes too but the user will need to add them manually. """ ...
Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph.
def graph_from_dot_file(path): """Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph. """ fd = file(path, 'rb') data = fd.read() fd.close() return graph_from_...
Creates a basic graph out of an edge list. The edge list has to be a list of tuples representing the nodes connected by the edge. The values can be anything: bool, int, float, str. If the graph is undirected by default, it is only calculated from one of the symmetric halves of the matrix.
def graph_from_edges(edge_list, node_prefix='', directed=False): """Creates a basic graph out of an edge list. The edge list has to be a list of tuples representing the nodes connected by the edge. The values can be anything: bool, int, float, str. If the graph is undirected by default, it...
Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary containing the program names as keys and their paths as values. Otherwise returns None
def __find_executables(path): """Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary containing the program names as keys and their paths as values. Otherwise returns None """ success = False progs...
Returns a string representation of the edge in dot language.
def to_string(self): """Returns a string representation of the edge in dot language. """ src = self.parse_node_ref( self.get_source() ) dst = self.parse_node_ref( self.get_destination() ) if isinstance(src, frozendict): edge = [ Subgraph(obj_dict=src).to_str...
Retrieve a node from the graph. Given a node's name the corresponding Node instance will be returned. If one or more nodes exist with that name a list of Node instances is returned. An empty list is returned otherwise.
def get_node(self, name): """Retrieve a node from the graph. Given a node's name the corresponding Node instance will be returned. If one or more nodes exist with that name a list of Node instances is returned. An empty list is returned otherwise. ...
Adds an edge object to the graph. It takes a edge object as its only argument and returns None.
def add_edge(self, graph_edge): """Adds an edge object to the graph. It takes a edge object as its only argument and returns None. """ if not isinstance(graph_edge, Edge): raise TypeError('add_edge() received a non edge class object: ' + str(graph_edge)) ...
Adds an subgraph object to the graph. It takes a subgraph object as its only argument and returns None.
def add_subgraph(self, sgraph): """Adds an subgraph object to the graph. It takes a subgraph object as its only argument and returns None. """ if not isinstance(sgraph, Subgraph) and not isinstance(sgraph, Cluster): raise TypeError('add_subgraph() received a...
Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from.
def to_string(self): """Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from. """ graph = list() if self.obj_dict.get('strict', None) is not None: if ...
Writes a graph to a file. Given a filename 'path' it will open/create and truncate such file and write on it a representation of the graph defined by the dot object and in the format specified by 'format'. The format 'raw' is used to dump the string representation of the...
def write(self, path, prog=None, format='raw'): """Writes a graph to a file. Given a filename 'path' it will open/create and truncate such file and write on it a representation of the graph defined by the dot object and in the format specified by 'format'. The format 'ra...
Creates and returns a Postscript representation of the graph. create will write the graph to a temporary dot file and process it with the program given by 'prog' (which defaults to 'twopi'), reading the Postscript output and returning it as a string is the operation is successful. ...
def create(self, prog=None, format='ps'): """Creates and returns a Postscript representation of the graph. create will write the graph to a temporary dot file and process it with the program given by 'prog' (which defaults to 'twopi'), reading the Postscript output and returning it as a...
Returns data as yaml-formatted string.
def dump_yaml(data, Dumper=_Dumper, default_flow_style=False): """Returns data as yaml-formatted string.""" content = yaml.dump(data, default_flow_style=default_flow_style, Dumper=Dumper) return content.strip()
Convenience function for loading yaml-encoded data from disk.
def load_yaml(filepath): """Convenience function for loading yaml-encoded data from disk.""" with open(filepath) as f: txt = f.read() return yaml.load(txt)
Get a shared memcached instance. This function shares the same memcached instance across nested invocations. This is done so that memcached connections can be kept to a minimum, but at the same time unnecessary extra reconnections are avoided. Typically an initial scope (using 'with' construct) is made...
def memcached_client(servers=config.memcached_uri, debug=config.debug_memcache): """Get a shared memcached instance. This function shares the same memcached instance across nested invocations. This is done so that memcached connections can be kept to a minimum, but at the same time unnecessary extra re...
Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections.
def pool_memcached_connections(func): """Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections. """ if isgeneratorfunction(func): def wrapper(*nargs...
memcached memoization function decorator. The wrapped function is expected to return a value that is stored to a memcached server, first translated by `to_cache` if provided. In the event of a cache hit, the data is translated by `from_cache` if provided, before being returned. If you do not want a res...
def memcached(servers, key=None, from_cache=None, to_cache=None, time=0, min_compress_len=0, debug=False): """memcached memoization function decorator. The wrapped function is expected to return a value that is stored to a memcached server, first translated by `to_cache` if provided. In the e...
Get the native memcache client. Returns: `memcache.Client` instance.
def client(self): """Get the native memcache client. Returns: `memcache.Client` instance. """ if self._client is None: self._client = Client_(self.servers) return self._client
See memcache.Client.
def set(self, key, val, time=0, min_compress_len=0): """See memcache.Client.""" if not self.servers: return key = self._qualified_key(key) hashed_key = self.key_hasher(key) val = (key, val) self.client.set(key=hashed_key, val=val, ...
See memcache.Client. Returns: object: A value if cached, else `self.miss`. Note that this differs from `memcache.Client`, which returns None on cache miss, and thus cannot cache the value None itself.
def get(self, key): """See memcache.Client. Returns: object: A value if cached, else `self.miss`. Note that this differs from `memcache.Client`, which returns None on cache miss, and thus cannot cache the value None itself. """ if not self.servers: ...
See memcache.Client.
def delete(self, key): """See memcache.Client.""" if self.servers: key = self._qualified_key(key) hashed_key = self.key_hasher(key) self.client.delete(hashed_key)
Drop existing entries from the cache. Args: hard (bool): If True, all current entries are flushed from the server(s), which affects all users. If False, only the local process is affected.
def flush(self, hard=False): """Drop existing entries from the cache. Args: hard (bool): If True, all current entries are flushed from the server(s), which affects all users. If False, only the local process is affected. """ if not self.server...
Depth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tupple containing a dictionary and two lists: 1. Generated spanning tree 2. Grap...
def depth_first_search(graph, root=None, filter=null()): """ Depth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tupple containing a diction...
Breadth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tuple containing a dictionary and a list. 1. Generated spanning tree 2. Graph's le...
def breadth_first_search(graph, root=None, filter=null()): """ Breadth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tuple containing a dictiona...
Make sure version is treated consistently
def normalize_variables(cls, variables): """Make sure version is treated consistently """ # if the version is False, empty string, etc, throw it out if variables.get('version', True) in ('', False, '_NO_VERSION', None): del variables['version'] return super(PackageRes...
Push an input source onto the lexer's input source stack.
def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, basestring): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile ...
Pop the input source stack.
def pop_source(self): "Pop the input source stack." self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() self.state = ' '
Get a token from the input stream (or from stack if it's nonempty)
def get_token(self): "Get a token from the input stream (or from stack if it's nonempty)" if self.pushback: tok = self.pushback.popleft() return tok # No pushback. Get a token. raw = self.read_token() # Handle inclusions if self.source is not None...
Emit a C-compiler-like, Emacs-friendly error-message leader.
def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if infile is None: infile = self.infile if lineno is None: lineno = self.lineno return "\"%s\", line %d: " % (infile, lineno)
Example (in yaml): type: per_family orderers: - packages: ['foo', 'bah'] type: version_split first_version: '4.0.5' - packages: ['python'] type: sorted descending: false default_order: type...
def to_pod(self): """ Example (in yaml): type: per_family orderers: - packages: ['foo', 'bah'] type: version_split first_version: '4.0.5' - packages: ['python'] type: sorted descending: false ...
Get the current shell. @returns The current shell this process is running in. Examples: bash tcsh
def shell(self): """Get the current shell. @returns The current shell this process is running in. Examples: bash tcsh """ from rez.shells import get_shell_types shells = set(get_shell_types()) if not shells: raise RezSystemError("no sh...
Get path containing rez binaries, or None if no binaries are available, or Rez is not a production install.
def rez_bin_path(self): """Get path containing rez binaries, or None if no binaries are available, or Rez is not a production install. """ binpath = None if sys.argv and sys.argv[0]: executable = sys.argv[0] path = which("rezolve", env={"PATH":os.path.dirn...
Get a string summarising the state of Rez as a whole. Returns: String.
def get_summary_string(self): """Get a string summarising the state of Rez as a whole. Returns: String. """ from rez.plugin_managers import plugin_manager txt = "Rez %s" % __version__ txt += "\n\n%s" % plugin_manager.get_summary_string() return txt
Clear all caches in Rez. Rez caches package contents and iteration during a python session. Thus newly released packages, and changes to existing packages, may not be picked up. You need to clear the cache for these changes to become visible. Args: hard (bool): Perf...
def clear_caches(self, hard=False): """Clear all caches in Rez. Rez caches package contents and iteration during a python session. Thus newly released packages, and changes to existing packages, may not be picked up. You need to clear the cache for these changes to become visibl...
Perform the solve.
def solve(self): """Perform the solve. """ with log_duration(self._print, "memcache get (resolve) took %s"): solver_dict = self._get_cached_solve() if solver_dict: self.from_cache = True self._set_result(solver_dict) else: self.fro...
Find a memcached resolve. If there is NOT a resolve timestamp: - fetch a non-timestamped memcache entry; - if no entry, then fail; - if packages have changed, then: - delete the entry; - fail; - if no packages in the entry have been r...
def _get_cached_solve(self): """Find a memcached resolve. If there is NOT a resolve timestamp: - fetch a non-timestamped memcache entry; - if no entry, then fail; - if packages have changed, then: - delete the entry; - fail; -...
Store a solve to memcached. If there is NOT a resolve timestamp: - store the solve to a non-timestamped entry. If there IS a resolve timestamp (let us call this T): - if NO newer package in the solve has been released since T, - then store the solve to a non-times...
def _set_cached_solve(self, solver_dict): """Store a solve to memcached. If there is NOT a resolve timestamp: - store the solve to a non-timestamped entry. If there IS a resolve timestamp (let us call this T): - if NO newer package in the solve has been released since T...
Makes a key suitable as a memcache entry.
def _memcache_key(self, timestamped=False): """Makes a key suitable as a memcache entry.""" request = tuple(map(str, self.package_requests)) repo_ids = [] for path in self.package_paths: repo = package_repository_manager.get_repository(path) repo_ids.append(repo.u...
Returns a Shell of the given type, or the current shell type if shell is None.
def create_shell(shell=None, **kwargs): """Returns a Shell of the given type, or the current shell type if shell is None.""" if not shell: shell = config.default_shell if not shell: from rez.system import system shell = system.shell from rez.plugin_managers impor...
Given a set of options related to shell startup, return the actual options that will be applied. @returns 4-tuple representing applied value of each option.
def startup_capabilities(cls, rcfile=False, norc=False, stdin=False, command=False): """ Given a set of options related to shell startup, return the actual options that will be applied. @returns 4-tuple representing applied value of each option. """ ...
Find an executable. Args: name (str): Program name. check_syspaths (bool): If True, check the standard system paths as well, if program was not found on current $PATH. Returns: str: Full filepath of executable.
def find_executable(cls, name, check_syspaths=False): """Find an executable. Args: name (str): Program name. check_syspaths (bool): If True, check the standard system paths as well, if program was not found on current $PATH. Returns: str: Ful...
Spawn a possibly interactive subshell. Args: context:_file File that must be sourced in the new shell, this configures the Rez environment. tmpdir: Tempfiles, if needed, should be created within this path. rcfile: Custom startup script. norc: Don't...
def spawn_shell(self, context_file, tmpdir, rcfile=None, norc=False, stdin=False, command=None, env=None, quiet=False, pre_command=None, add_rez=True, package_commands_sourced_first=None, **Popen_args): """Spawn a possibly interactive subshell. ...
Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the file to be uploaded. :param filename: The pathname of the file to be uploaded. :param signer: The identifier of the signer of the file. ...
def upload_file(self, metadata, filename, signer=None, sign_password=None, filetype='sdist', pyversion='source', keystore=None): """ Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and versio...
Copy a package from one package repository to another. This copies the package definition and payload. The package can also be re-named and/or re-versioned using the `dest_name` and `dest_version` args. The result is a dict describing which package variants were and were not copied. For example: ...
def copy_package(package, dest_repository, variants=None, shallow=False, dest_name=None, dest_version=None, overwrite=False, force=False, follow_symlinks=False, dry_run=False, keep_timestamp=False, skip_payload=False, overrides=None, verbose=False): """Copy a packa...
Return list of nodes as close as possible to the ordering in node_list, but with child nodes earlier in the list than parents.
def _get_dependency_order(g, node_list): """Return list of nodes as close as possible to the ordering in node_list, but with child nodes earlier in the list than parents.""" access_ = accessibility(g) deps = dict((k, set(v) - set([k])) for k, v in access_.iteritems()) nodes = node_list + list(set(g....
print shortened version of '==X|==Y|==Z' ranged requests.
def _short_req_str(package_request): """print shortened version of '==X|==Y|==Z' ranged requests.""" if not package_request.conflict: versions = package_request.range.to_versions() if versions and len(versions) == len(package_request.range) \ and len(versions) > 1: re...
It is important that this property is calculated lazily. Getting the 'requires' attribute may trigger a package load, which may be avoided if this variant is reduced away before that happens.
def requires_list(self): """ It is important that this property is calculated lazily. Getting the 'requires' attribute may trigger a package load, which may be avoided if this variant is reduced away before that happens. """ requires = self.variant.get_requires(build_requ...
Sort variants from most correct to consume, to least. Sort rules: version_priority: - sort by highest versions of packages shared with request; - THEN least number of additional packages added to solve; - THEN highest versions of additional packages; - THEN alphabetical...
def sort(self): """Sort variants from most correct to consume, to least. Sort rules: version_priority: - sort by highest versions of packages shared with request; - THEN least number of additional packages added to solve; - THEN highest versions of additional packages; ...
Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects.
def get_intersection(self, range_): """Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects. """ result = [] for entry in self.entries: ...
Remove variants whose version fall outside of the given range.
def intersect(self, range_): self.solver.intersection_broad_tests_count += 1 """Remove variants whose version fall outside of the given range.""" if range_.is_any(): return self if self.solver.optimised: if range_ in self.been_intersected_with: r...
Remove variants whos dependencies conflict with the given package request. Returns: (VariantSlice, [Reduction]) tuple, where slice may be None if all variants were reduced.
def reduce_by(self, package_request): """Remove variants whos dependencies conflict with the given package request. Returns: (VariantSlice, [Reduction]) tuple, where slice may be None if all variants were reduced. """ if self.pr: reqstr = _sho...
Split the slice. Returns: (`_PackageVariantSlice`, `_PackageVariantSlice`) tuple, where the first is the preferred slice.
def split(self): """Split the slice. Returns: (`_PackageVariantSlice`, `_PackageVariantSlice`) tuple, where the first is the preferred slice. """ # We sort here in the split in order to sort as late as possible. # Because splits usually happen after inte...
Extract a common dependency. Note that conflict dependencies are never extracted, they are always resolved via reduction.
def extract(self): """Extract a common dependency. Note that conflict dependencies are never extracted, they are always resolved via reduction. """ if not self.extractable: return self, None extractable = self.common_fams - self.extracted_fams # the...
Sort entries by version. The order is typically descending, but package order functions can change this.
def sort_versions(self): """Sort entries by version. The order is typically descending, but package order functions can change this. """ if self.sorted: return for orderer in (self.solver.package_orderers or []): entries = orderer.reorder(self.en...
Get a list of variants from the cache. Args: package_name (str): Name of package. range_ (`VersionRange`): Package version range. Returns: `_PackageVariantSlice` object.
def get_variant_slice(self, package_name, range_): """Get a list of variants from the cache. Args: package_name (str): Name of package. range_ (`VersionRange`): Package version range. Returns: `_PackageVariantSlice` object. """ variant_list =...
Intersect this scope with a package range. Returns: A new copy of this scope, with variants whos version fall outside of the given range removed. If there were no removals, self is returned. If all variants were removed, None is returned.
def intersect(self, range_): """Intersect this scope with a package range. Returns: A new copy of this scope, with variants whos version fall outside of the given range removed. If there were no removals, self is returned. If all variants were removed, None is return...
Reduce this scope wrt a package request. Returns: A (_PackageScope, [Reduction]) tuple, where the scope is a new scope copy with reductions applied, or self if there were no reductions, or None if the scope was completely reduced.
def reduce_by(self, package_request): """Reduce this scope wrt a package request. Returns: A (_PackageScope, [Reduction]) tuple, where the scope is a new scope copy with reductions applied, or self if there were no reductions, or None if the scope was completely redu...
Extract a common dependency. Returns: A (_PackageScope, Requirement) tuple, containing the new scope copy with the extraction, and the extracted package range. If no package was extracted, then (self,None) is returned.
def extract(self): """Extract a common dependency. Returns: A (_PackageScope, Requirement) tuple, containing the new scope copy with the extraction, and the extracted package range. If no package was extracted, then (self,None) is returned. """ if not...
Split the scope. Returns: A (_PackageScope, _PackageScope) tuple, where the first scope is guaranteed to have a common dependency. Or None, if splitting is not applicable to this scope.
def split(self): """Split the scope. Returns: A (_PackageScope, _PackageScope) tuple, where the first scope is guaranteed to have a common dependency. Or None, if splitting is not applicable to this scope. """ if self.package_request.conflict or (len(...
Attempt to solve the phase.
def solve(self): """Attempt to solve the phase.""" if self.status != SolverStatus.pending: return self scopes = self.scopes[:] failure_reason = None extractions = {} changed_scopes_i = self.changed_scopes_i.copy() def _create_phase(status=None): ...
Remove conflict requests, detect cyclic dependencies, and reorder packages wrt dependency and then request order. Returns: A new copy of the phase with conflict requests removed and packages correctly ordered; or, if cyclic dependencies were detected, a new phase mar...
def finalise(self): """Remove conflict requests, detect cyclic dependencies, and reorder packages wrt dependency and then request order. Returns: A new copy of the phase with conflict requests removed and packages correctly ordered; or, if cyclic dependencies were detect...
Split the phase. When a phase is exhausted, it gets split into a pair of phases to be further solved. The split happens like so: 1) Select the first unsolved package scope. 2) Find some common dependency in the first N variants of the scope. 3) Split the scope into two: [:N] and...
def split(self): """Split the phase. When a phase is exhausted, it gets split into a pair of phases to be further solved. The split happens like so: 1) Select the first unsolved package scope. 2) Find some common dependency in the first N variants of the scope. 3) Split ...
Get the resolve graph. The resolve graph shows what packages were resolved, and the relationships between them. A failed phase also has a graph, which will shows the conflict(s) that caused the resolve to fail. Returns: A pygraph.digraph object.
def get_graph(self): """Get the resolve graph. The resolve graph shows what packages were resolved, and the relationships between them. A failed phase also has a graph, which will shows the conflict(s) that caused the resolve to fail. Returns: A pygraph.digraph obje...
Return the current status of the solve. Returns: SolverStatus: Enum representation of the state of the solver.
def status(self): """Return the current status of the solve. Returns: SolverStatus: Enum representation of the state of the solver. """ if self.request_list.conflict: return SolverStatus.failed if self.callback_return == SolverCallbackReturn.fail: ...
Return the number of failed solve steps that have been executed. Note that num_solves is inclusive of failures.
def num_fails(self): """Return the number of failed solve steps that have been executed. Note that num_solves is inclusive of failures.""" n = len(self.failed_phase_list) if self.phase_stack[-1].status in (SolverStatus.failed, SolverStatus.cyclic): n += 1 return n
Return a list of PackageVariant objects, or None if the resolve did not complete or was unsuccessful.
def resolved_packages(self): """Return a list of PackageVariant objects, or None if the resolve did not complete or was unsuccessful. """ if (self.status != SolverStatus.solved): return None final_phase = self.phase_stack[-1] return final_phase._get_solved_va...
Reset the solver, removing any current solve.
def reset(self): """Reset the solver, removing any current solve.""" if not self.request_list.conflict: phase = _ResolvePhase(self.request_list.requirements, solver=self) self.pr("resetting...") self._init() self._push_phase(phase)
Attempt to solve the request.
def solve(self): """Attempt to solve the request. """ if self.solve_begun: raise ResolveError("cannot run solve() on a solve that has " "already been started") t1 = time.time() pt1 = package_repo_stats.package_load_time # itera...
Perform a single solve step.
def solve_step(self): """Perform a single solve step. """ self.solve_begun = True if self.status != SolverStatus.unsolved: return if self.pr: self.pr.header("SOLVE #%d (%d fails so far)...", self.solve_count + 1, self.num_fails)...
Get packages involved in a failure. Args: failure_index: See `failure_reason`. Returns: A list of Requirement objects.
def failure_packages(self, failure_index=None): """Get packages involved in a failure. Args: failure_index: See `failure_reason`. Returns: A list of Requirement objects. """ phase, _ = self._get_failed_phase(failure_index) fr = phase.failure_reas...
Get the reason for a failure. Args: failure_index: Index of the fail to return the graph for (can be negative). If None, the most appropriate failure is chosen according to these rules: - If the fail is cyclic, the most recent fail (the one containing...
def failure_reason(self, failure_index=None): """Get the reason for a failure. Args: failure_index: Index of the fail to return the graph for (can be negative). If None, the most appropriate failure is chosen according to these rules: - If the...
Returns the most recent solve graph. This gives a graph showing the latest state of the solve. The specific graph returned depends on the solve status. When status is: unsolved: latest unsolved graph is returned; solved: final solved graph is returned; failed: most appropria...
def get_graph(self): """Returns the most recent solve graph. This gives a graph showing the latest state of the solve. The specific graph returned depends on the solve status. When status is: unsolved: latest unsolved graph is returned; solved: final solved graph is returned; ...
Returns a graph showing a solve failure. Args: failure_index: See `failure_reason` Returns: A pygraph.digraph object.
def get_fail_graph(self, failure_index=None): """Returns a graph showing a solve failure. Args: failure_index: See `failure_reason` Returns: A pygraph.digraph object. """ phase, _ = self._get_failed_phase(failure_index) return phase.get_graph()
Print a formatted summary of the current solve state.
def dump(self): """Print a formatted summary of the current solve state.""" from rez.utils.formatting import columnise rows = [] for i, phase in enumerate(self.phase_stack): rows.append((self._depth_label(i), phase.status, str(phase))) print "status: %s (%s)" % (sel...
Temporarily make `path` writable, if possible. Does nothing if: - config setting 'make_package_temporarily_writable' is False; - this can't be done (eg we don't own `path`). Args: path (str): Path to make temporarily writable
def make_path_writable(path): """Temporarily make `path` writable, if possible. Does nothing if: - config setting 'make_package_temporarily_writable' is False; - this can't be done (eg we don't own `path`). Args: path (str): Path to make temporarily writable """ from rez.co...
Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found.
def get_existing_path(path, topmost_path=None): """Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found. ...
Safe makedirs. Works in a multithreaded scenario.
def safe_makedirs(path): """Safe makedirs. Works in a multithreaded scenario. """ if not os.path.exists(path): try: os.makedirs(path) except OSError: if not os.path.exists(path): raise
Safely remove the given file or directory. Works in a multithreaded scenario.
def safe_remove(path): """Safely remove the given file or directory. Works in a multithreaded scenario. """ if not os.path.exists(path): return try: if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) else: os.remove(path) ex...
Create symlink that overwrites any existing target.
def replacing_symlink(source, link_name): """Create symlink that overwrites any existing target. """ with make_tmp_name(link_name) as tmp_link_name: os.symlink(source, tmp_link_name) replace_file_or_dir(link_name, tmp_link_name)