id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,600
nerdvegas/rez
src/rez/vendor/pygraph/mixins/labeling.py
labeling.edge_weight
def edge_weight(self, edge): """ Get the weight of an edge. @type edge: edge @param edge: One edge. @rtype: number @return: Edge weight. """ return self.get_edge_properties( edge ).setdefault( self.WEIGHT_ATTRIBUTE_NAME, self.DEFAULT_WEIGHT )
python
def edge_weight(self, edge): """ Get the weight of an edge. @type edge: edge @param edge: One edge. @rtype: number @return: Edge weight. """ return self.get_edge_properties( edge ).setdefault( self.WEIGHT_ATTRIBUTE_NAME, self.DEFAULT_WEIGHT )
[ "def", "edge_weight", "(", "self", ",", "edge", ")", ":", "return", "self", ".", "get_edge_properties", "(", "edge", ")", ".", "setdefault", "(", "self", ".", "WEIGHT_ATTRIBUTE_NAME", ",", "self", ".", "DEFAULT_WEIGHT", ")" ]
Get the weight of an edge. @type edge: edge @param edge: One edge. @rtype: number @return: Edge weight.
[ "Get", "the", "weight", "of", "an", "edge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L66-L76
232,601
nerdvegas/rez
src/rez/vendor/pygraph/mixins/labeling.py
labeling.set_edge_weight
def set_edge_weight(self, edge, wt): """ Set the weight of an edge. @type edge: edge @param edge: One edge. @type wt: number @param wt: Edge weight. """ self.set_edge_properties(edge, weight=wt ) if not self.DIRECTED: self.set_edge_properties((edge[1], edge[0]) , weight=wt )
python
def set_edge_weight(self, edge, wt): """ Set the weight of an edge. @type edge: edge @param edge: One edge. @type wt: number @param wt: Edge weight. """ self.set_edge_properties(edge, weight=wt ) if not self.DIRECTED: self.set_edge_properties((edge[1], edge[0]) , weight=wt )
[ "def", "set_edge_weight", "(", "self", ",", "edge", ",", "wt", ")", ":", "self", ".", "set_edge_properties", "(", "edge", ",", "weight", "=", "wt", ")", "if", "not", "self", ".", "DIRECTED", ":", "self", ".", "set_edge_properties", "(", "(", "edge", "[", "1", "]", ",", "edge", "[", "0", "]", ")", ",", "weight", "=", "wt", ")" ]
Set the weight of an edge. @type edge: edge @param edge: One edge. @type wt: number @param wt: Edge weight.
[ "Set", "the", "weight", "of", "an", "edge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L79-L91
232,602
nerdvegas/rez
src/rez/vendor/pygraph/mixins/labeling.py
labeling.edge_label
def edge_label(self, edge): """ Get the label of an edge. @type edge: edge @param edge: One edge. @rtype: string @return: Edge label """ return self.get_edge_properties( edge ).setdefault( self.LABEL_ATTRIBUTE_NAME, self.DEFAULT_LABEL )
python
def edge_label(self, edge): """ Get the label of an edge. @type edge: edge @param edge: One edge. @rtype: string @return: Edge label """ return self.get_edge_properties( edge ).setdefault( self.LABEL_ATTRIBUTE_NAME, self.DEFAULT_LABEL )
[ "def", "edge_label", "(", "self", ",", "edge", ")", ":", "return", "self", ".", "get_edge_properties", "(", "edge", ")", ".", "setdefault", "(", "self", ".", "LABEL_ATTRIBUTE_NAME", ",", "self", ".", "DEFAULT_LABEL", ")" ]
Get the label of an edge. @type edge: edge @param edge: One edge. @rtype: string @return: Edge label
[ "Get", "the", "label", "of", "an", "edge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L94-L104
232,603
nerdvegas/rez
src/rez/vendor/pygraph/mixins/labeling.py
labeling.set_edge_label
def set_edge_label(self, edge, label): """ Set the label of an edge. @type edge: edge @param edge: One edge. @type label: string @param label: Edge label. """ self.set_edge_properties(edge, label=label ) if not self.DIRECTED: self.set_edge_properties((edge[1], edge[0]) , label=label )
python
def set_edge_label(self, edge, label): """ Set the label of an edge. @type edge: edge @param edge: One edge. @type label: string @param label: Edge label. """ self.set_edge_properties(edge, label=label ) if not self.DIRECTED: self.set_edge_properties((edge[1], edge[0]) , label=label )
[ "def", "set_edge_label", "(", "self", ",", "edge", ",", "label", ")", ":", "self", ".", "set_edge_properties", "(", "edge", ",", "label", "=", "label", ")", "if", "not", "self", ".", "DIRECTED", ":", "self", ".", "set_edge_properties", "(", "(", "edge", "[", "1", "]", ",", "edge", "[", "0", "]", ")", ",", "label", "=", "label", ")" ]
Set the label of an edge. @type edge: edge @param edge: One edge. @type label: string @param label: Edge label.
[ "Set", "the", "label", "of", "an", "edge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L106-L118
232,604
nerdvegas/rez
src/rez/vendor/pygraph/mixins/labeling.py
labeling.add_edge_attribute
def add_edge_attribute(self, edge, attr): """ Add attribute to the given edge. @type edge: edge @param edge: One edge. @type attr: tuple @param attr: Node attribute specified as a tuple in the form (attribute, value). """ self.edge_attr[edge] = self.edge_attributes(edge) + [attr] if (not self.DIRECTED and edge[0] != edge[1]): self.edge_attr[(edge[1],edge[0])] = self.edge_attributes((edge[1], edge[0])) + [attr]
python
def add_edge_attribute(self, edge, attr): """ Add attribute to the given edge. @type edge: edge @param edge: One edge. @type attr: tuple @param attr: Node attribute specified as a tuple in the form (attribute, value). """ self.edge_attr[edge] = self.edge_attributes(edge) + [attr] if (not self.DIRECTED and edge[0] != edge[1]): self.edge_attr[(edge[1],edge[0])] = self.edge_attributes((edge[1], edge[0])) + [attr]
[ "def", "add_edge_attribute", "(", "self", ",", "edge", ",", "attr", ")", ":", "self", ".", "edge_attr", "[", "edge", "]", "=", "self", ".", "edge_attributes", "(", "edge", ")", "+", "[", "attr", "]", "if", "(", "not", "self", ".", "DIRECTED", "and", "edge", "[", "0", "]", "!=", "edge", "[", "1", "]", ")", ":", "self", ".", "edge_attr", "[", "(", "edge", "[", "1", "]", ",", "edge", "[", "0", "]", ")", "]", "=", "self", ".", "edge_attributes", "(", "(", "edge", "[", "1", "]", ",", "edge", "[", "0", "]", ")", ")", "+", "[", "attr", "]" ]
Add attribute to the given edge. @type edge: edge @param edge: One edge. @type attr: tuple @param attr: Node attribute specified as a tuple in the form (attribute, value).
[ "Add", "attribute", "to", "the", "given", "edge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L128-L141
232,605
nerdvegas/rez
src/rez/vendor/pygraph/mixins/labeling.py
labeling.add_node_attribute
def add_node_attribute(self, node, attr): """ Add attribute to the given node. @type node: node @param node: Node identifier @type attr: tuple @param attr: Node attribute specified as a tuple in the form (attribute, value). """ self.node_attr[node] = self.node_attr[node] + [attr]
python
def add_node_attribute(self, node, attr): """ Add attribute to the given node. @type node: node @param node: Node identifier @type attr: tuple @param attr: Node attribute specified as a tuple in the form (attribute, value). """ self.node_attr[node] = self.node_attr[node] + [attr]
[ "def", "add_node_attribute", "(", "self", ",", "node", ",", "attr", ")", ":", "self", ".", "node_attr", "[", "node", "]", "=", "self", ".", "node_attr", "[", "node", "]", "+", "[", "attr", "]" ]
Add attribute to the given node. @type node: node @param node: Node identifier @type attr: tuple @param attr: Node attribute specified as a tuple in the form (attribute, value).
[ "Add", "attribute", "to", "the", "given", "node", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L157-L167
232,606
nerdvegas/rez
src/rez/suite.py
Suite.activation_shell_code
def activation_shell_code(self, shell=None): """Get shell code that should be run to activate this suite.""" from rez.shells import create_shell from rez.rex import RexExecutor executor = RexExecutor(interpreter=create_shell(shell), parent_variables=["PATH"], shebang=False) executor.env.PATH.append(self.tools_path) return executor.get_output().strip()
python
def activation_shell_code(self, shell=None): """Get shell code that should be run to activate this suite.""" from rez.shells import create_shell from rez.rex import RexExecutor executor = RexExecutor(interpreter=create_shell(shell), parent_variables=["PATH"], shebang=False) executor.env.PATH.append(self.tools_path) return executor.get_output().strip()
[ "def", "activation_shell_code", "(", "self", ",", "shell", "=", "None", ")", ":", "from", "rez", ".", "shells", "import", "create_shell", "from", "rez", ".", "rex", "import", "RexExecutor", "executor", "=", "RexExecutor", "(", "interpreter", "=", "create_shell", "(", "shell", ")", ",", "parent_variables", "=", "[", "\"PATH\"", "]", ",", "shebang", "=", "False", ")", "executor", ".", "env", ".", "PATH", ".", "append", "(", "self", ".", "tools_path", ")", "return", "executor", ".", "get_output", "(", ")", ".", "strip", "(", ")" ]
Get shell code that should be run to activate this suite.
[ "Get", "shell", "code", "that", "should", "be", "run", "to", "activate", "this", "suite", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L68-L77
232,607
nerdvegas/rez
src/rez/suite.py
Suite.context
def context(self, name): """Get a context. Args: name (str): Name to store the context under. Returns: `ResolvedContext` object. """ data = self._context(name) context = data.get("context") if context: return context assert self.load_path context_path = os.path.join(self.load_path, "contexts", "%s.rxt" % name) context = ResolvedContext.load(context_path) data["context"] = context data["loaded"] = True return context
python
def context(self, name): """Get a context. Args: name (str): Name to store the context under. Returns: `ResolvedContext` object. """ data = self._context(name) context = data.get("context") if context: return context assert self.load_path context_path = os.path.join(self.load_path, "contexts", "%s.rxt" % name) context = ResolvedContext.load(context_path) data["context"] = context data["loaded"] = True return context
[ "def", "context", "(", "self", ",", "name", ")", ":", "data", "=", "self", ".", "_context", "(", "name", ")", "context", "=", "data", ".", "get", "(", "\"context\"", ")", "if", "context", ":", "return", "context", "assert", "self", ".", "load_path", "context_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "load_path", ",", "\"contexts\"", ",", "\"%s.rxt\"", "%", "name", ")", "context", "=", "ResolvedContext", ".", "load", "(", "context_path", ")", "data", "[", "\"context\"", "]", "=", "context", "data", "[", "\"loaded\"", "]", "=", "True", "return", "context" ]
Get a context. Args: name (str): Name to store the context under. Returns: `ResolvedContext` object.
[ "Get", "a", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L82-L101
232,608
nerdvegas/rez
src/rez/suite.py
Suite.add_context
def add_context(self, name, context, prefix_char=None): """Add a context to the suite. Args: name (str): Name to store the context under. context (ResolvedContext): Context to add. """ if name in self.contexts: raise SuiteError("Context already in suite: %r" % name) if not context.success: raise SuiteError("Context is not resolved: %r" % name) self.contexts[name] = dict(name=name, context=context.copy(), tool_aliases={}, hidden_tools=set(), priority=self._next_priority, prefix_char=prefix_char) self._flush_tools()
python
def add_context(self, name, context, prefix_char=None): """Add a context to the suite. Args: name (str): Name to store the context under. context (ResolvedContext): Context to add. """ if name in self.contexts: raise SuiteError("Context already in suite: %r" % name) if not context.success: raise SuiteError("Context is not resolved: %r" % name) self.contexts[name] = dict(name=name, context=context.copy(), tool_aliases={}, hidden_tools=set(), priority=self._next_priority, prefix_char=prefix_char) self._flush_tools()
[ "def", "add_context", "(", "self", ",", "name", ",", "context", ",", "prefix_char", "=", "None", ")", ":", "if", "name", "in", "self", ".", "contexts", ":", "raise", "SuiteError", "(", "\"Context already in suite: %r\"", "%", "name", ")", "if", "not", "context", ".", "success", ":", "raise", "SuiteError", "(", "\"Context is not resolved: %r\"", "%", "name", ")", "self", ".", "contexts", "[", "name", "]", "=", "dict", "(", "name", "=", "name", ",", "context", "=", "context", ".", "copy", "(", ")", ",", "tool_aliases", "=", "{", "}", ",", "hidden_tools", "=", "set", "(", ")", ",", "priority", "=", "self", ".", "_next_priority", ",", "prefix_char", "=", "prefix_char", ")", "self", ".", "_flush_tools", "(", ")" ]
Add a context to the suite. Args: name (str): Name to store the context under. context (ResolvedContext): Context to add.
[ "Add", "a", "context", "to", "the", "suite", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L103-L121
232,609
nerdvegas/rez
src/rez/suite.py
Suite.find_contexts
def find_contexts(self, in_request=None, in_resolve=None): """Find contexts in the suite based on search criteria. Args: in_request (str): Match contexts that contain the given package in their request. in_resolve (str or `Requirement`): Match contexts that contain the given package in their resolve. You can also supply a conflict requirement - '!foo' will match any contexts whos resolve does not contain any version of package 'foo'. Returns: List of context names that match the search criteria. """ names = self.context_names if in_request: def _in_request(name): context = self.context(name) packages = set(x.name for x in context.requested_packages(True)) return (in_request in packages) names = [x for x in names if _in_request(x)] if in_resolve: if isinstance(in_resolve, basestring): in_resolve = PackageRequest(in_resolve) def _in_resolve(name): context = self.context(name) variant = context.get_resolved_package(in_resolve.name) if variant: overlap = (variant.version in in_resolve.range) return ((in_resolve.conflict and not overlap) or (overlap and not in_resolve.conflict)) else: return in_resolve.conflict names = [x for x in names if _in_resolve(x)] return names
python
def find_contexts(self, in_request=None, in_resolve=None): """Find contexts in the suite based on search criteria. Args: in_request (str): Match contexts that contain the given package in their request. in_resolve (str or `Requirement`): Match contexts that contain the given package in their resolve. You can also supply a conflict requirement - '!foo' will match any contexts whos resolve does not contain any version of package 'foo'. Returns: List of context names that match the search criteria. """ names = self.context_names if in_request: def _in_request(name): context = self.context(name) packages = set(x.name for x in context.requested_packages(True)) return (in_request in packages) names = [x for x in names if _in_request(x)] if in_resolve: if isinstance(in_resolve, basestring): in_resolve = PackageRequest(in_resolve) def _in_resolve(name): context = self.context(name) variant = context.get_resolved_package(in_resolve.name) if variant: overlap = (variant.version in in_resolve.range) return ((in_resolve.conflict and not overlap) or (overlap and not in_resolve.conflict)) else: return in_resolve.conflict names = [x for x in names if _in_resolve(x)] return names
[ "def", "find_contexts", "(", "self", ",", "in_request", "=", "None", ",", "in_resolve", "=", "None", ")", ":", "names", "=", "self", ".", "context_names", "if", "in_request", ":", "def", "_in_request", "(", "name", ")", ":", "context", "=", "self", ".", "context", "(", "name", ")", "packages", "=", "set", "(", "x", ".", "name", "for", "x", "in", "context", ".", "requested_packages", "(", "True", ")", ")", "return", "(", "in_request", "in", "packages", ")", "names", "=", "[", "x", "for", "x", "in", "names", "if", "_in_request", "(", "x", ")", "]", "if", "in_resolve", ":", "if", "isinstance", "(", "in_resolve", ",", "basestring", ")", ":", "in_resolve", "=", "PackageRequest", "(", "in_resolve", ")", "def", "_in_resolve", "(", "name", ")", ":", "context", "=", "self", ".", "context", "(", "name", ")", "variant", "=", "context", ".", "get_resolved_package", "(", "in_resolve", ".", "name", ")", "if", "variant", ":", "overlap", "=", "(", "variant", ".", "version", "in", "in_resolve", ".", "range", ")", "return", "(", "(", "in_resolve", ".", "conflict", "and", "not", "overlap", ")", "or", "(", "overlap", "and", "not", "in_resolve", ".", "conflict", ")", ")", "else", ":", "return", "in_resolve", ".", "conflict", "names", "=", "[", "x", "for", "x", "in", "names", "if", "_in_resolve", "(", "x", ")", "]", "return", "names" ]
Find contexts in the suite based on search criteria. Args: in_request (str): Match contexts that contain the given package in their request. in_resolve (str or `Requirement`): Match contexts that contain the given package in their resolve. You can also supply a conflict requirement - '!foo' will match any contexts whos resolve does not contain any version of package 'foo'. Returns: List of context names that match the search criteria.
[ "Find", "contexts", "in", "the", "suite", "based", "on", "search", "criteria", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L123-L161
232,610
nerdvegas/rez
src/rez/suite.py
Suite.remove_context
def remove_context(self, name): """Remove a context from the suite. Args: name (str): Name of the context to remove. """ self._context(name) del self.contexts[name] self._flush_tools()
python
def remove_context(self, name): """Remove a context from the suite. Args: name (str): Name of the context to remove. """ self._context(name) del self.contexts[name] self._flush_tools()
[ "def", "remove_context", "(", "self", ",", "name", ")", ":", "self", ".", "_context", "(", "name", ")", "del", "self", ".", "contexts", "[", "name", "]", "self", ".", "_flush_tools", "(", ")" ]
Remove a context from the suite. Args: name (str): Name of the context to remove.
[ "Remove", "a", "context", "from", "the", "suite", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L163-L171
232,611
nerdvegas/rez
src/rez/suite.py
Suite.set_context_prefix
def set_context_prefix(self, name, prefix): """Set a context's prefix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as '<prefix>foo' in the suite's bin path. Args: name (str): Name of the context to prefix. prefix (str): Prefix to apply to tools. """ data = self._context(name) data["prefix"] = prefix self._flush_tools()
python
def set_context_prefix(self, name, prefix): """Set a context's prefix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as '<prefix>foo' in the suite's bin path. Args: name (str): Name of the context to prefix. prefix (str): Prefix to apply to tools. """ data = self._context(name) data["prefix"] = prefix self._flush_tools()
[ "def", "set_context_prefix", "(", "self", ",", "name", ",", "prefix", ")", ":", "data", "=", "self", ".", "_context", "(", "name", ")", "data", "[", "\"prefix\"", "]", "=", "prefix", "self", ".", "_flush_tools", "(", ")" ]
Set a context's prefix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as '<prefix>foo' in the suite's bin path. Args: name (str): Name of the context to prefix. prefix (str): Prefix to apply to tools.
[ "Set", "a", "context", "s", "prefix", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L173-L186
232,612
nerdvegas/rez
src/rez/suite.py
Suite.set_context_suffix
def set_context_suffix(self, name, suffix): """Set a context's suffix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as 'foo<suffix>' in the suite's bin path. Args: name (str): Name of the context to suffix. suffix (str): Suffix to apply to tools. """ data = self._context(name) data["suffix"] = suffix self._flush_tools()
python
def set_context_suffix(self, name, suffix): """Set a context's suffix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as 'foo<suffix>' in the suite's bin path. Args: name (str): Name of the context to suffix. suffix (str): Suffix to apply to tools. """ data = self._context(name) data["suffix"] = suffix self._flush_tools()
[ "def", "set_context_suffix", "(", "self", ",", "name", ",", "suffix", ")", ":", "data", "=", "self", ".", "_context", "(", "name", ")", "data", "[", "\"suffix\"", "]", "=", "suffix", "self", ".", "_flush_tools", "(", ")" ]
Set a context's suffix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as 'foo<suffix>' in the suite's bin path. Args: name (str): Name of the context to suffix. suffix (str): Suffix to apply to tools.
[ "Set", "a", "context", "s", "suffix", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L196-L209
232,613
nerdvegas/rez
src/rez/suite.py
Suite.bump_context
def bump_context(self, name): """Causes the context's tools to take priority over all others.""" data = self._context(name) data["priority"] = self._next_priority self._flush_tools()
python
def bump_context(self, name): """Causes the context's tools to take priority over all others.""" data = self._context(name) data["priority"] = self._next_priority self._flush_tools()
[ "def", "bump_context", "(", "self", ",", "name", ")", ":", "data", "=", "self", ".", "_context", "(", "name", ")", "data", "[", "\"priority\"", "]", "=", "self", ".", "_next_priority", "self", ".", "_flush_tools", "(", ")" ]
Causes the context's tools to take priority over all others.
[ "Causes", "the", "context", "s", "tools", "to", "take", "priority", "over", "all", "others", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L219-L223
232,614
nerdvegas/rez
src/rez/suite.py
Suite.hide_tool
def hide_tool(self, context_name, tool_name): """Hide a tool so that it is not exposed in the suite. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to hide. """ data = self._context(context_name) hidden_tools = data["hidden_tools"] if tool_name not in hidden_tools: self._validate_tool(context_name, tool_name) hidden_tools.add(tool_name) self._flush_tools()
python
def hide_tool(self, context_name, tool_name): """Hide a tool so that it is not exposed in the suite. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to hide. """ data = self._context(context_name) hidden_tools = data["hidden_tools"] if tool_name not in hidden_tools: self._validate_tool(context_name, tool_name) hidden_tools.add(tool_name) self._flush_tools()
[ "def", "hide_tool", "(", "self", ",", "context_name", ",", "tool_name", ")", ":", "data", "=", "self", ".", "_context", "(", "context_name", ")", "hidden_tools", "=", "data", "[", "\"hidden_tools\"", "]", "if", "tool_name", "not", "in", "hidden_tools", ":", "self", ".", "_validate_tool", "(", "context_name", ",", "tool_name", ")", "hidden_tools", ".", "add", "(", "tool_name", ")", "self", ".", "_flush_tools", "(", ")" ]
Hide a tool so that it is not exposed in the suite. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to hide.
[ "Hide", "a", "tool", "so", "that", "it", "is", "not", "exposed", "in", "the", "suite", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L225-L237
232,615
nerdvegas/rez
src/rez/suite.py
Suite.unhide_tool
def unhide_tool(self, context_name, tool_name): """Unhide a tool so that it may be exposed in a suite. Note that unhiding a tool doesn't guarantee it can be seen - a tool of the same name from a different context may be overriding it. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to unhide. """ data = self._context(context_name) hidden_tools = data["hidden_tools"] if tool_name in hidden_tools: hidden_tools.remove(tool_name) self._flush_tools()
python
def unhide_tool(self, context_name, tool_name): """Unhide a tool so that it may be exposed in a suite. Note that unhiding a tool doesn't guarantee it can be seen - a tool of the same name from a different context may be overriding it. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to unhide. """ data = self._context(context_name) hidden_tools = data["hidden_tools"] if tool_name in hidden_tools: hidden_tools.remove(tool_name) self._flush_tools()
[ "def", "unhide_tool", "(", "self", ",", "context_name", ",", "tool_name", ")", ":", "data", "=", "self", ".", "_context", "(", "context_name", ")", "hidden_tools", "=", "data", "[", "\"hidden_tools\"", "]", "if", "tool_name", "in", "hidden_tools", ":", "hidden_tools", ".", "remove", "(", "tool_name", ")", "self", ".", "_flush_tools", "(", ")" ]
Unhide a tool so that it may be exposed in a suite. Note that unhiding a tool doesn't guarantee it can be seen - a tool of the same name from a different context may be overriding it. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to unhide.
[ "Unhide", "a", "tool", "so", "that", "it", "may", "be", "exposed", "in", "a", "suite", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L239-L253
232,616
nerdvegas/rez
src/rez/suite.py
Suite.alias_tool
def alias_tool(self, context_name, tool_name, tool_alias): """Register an alias for a specific tool. Note that a tool alias takes precedence over a context prefix/suffix. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to alias. tool_alias (str): Alias to give the tool. """ data = self._context(context_name) aliases = data["tool_aliases"] if tool_name in aliases: raise SuiteError("Tool %r in context %r is already aliased to %r" % (tool_name, context_name, aliases[tool_name])) self._validate_tool(context_name, tool_name) aliases[tool_name] = tool_alias self._flush_tools()
python
def alias_tool(self, context_name, tool_name, tool_alias): """Register an alias for a specific tool. Note that a tool alias takes precedence over a context prefix/suffix. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to alias. tool_alias (str): Alias to give the tool. """ data = self._context(context_name) aliases = data["tool_aliases"] if tool_name in aliases: raise SuiteError("Tool %r in context %r is already aliased to %r" % (tool_name, context_name, aliases[tool_name])) self._validate_tool(context_name, tool_name) aliases[tool_name] = tool_alias self._flush_tools()
[ "def", "alias_tool", "(", "self", ",", "context_name", ",", "tool_name", ",", "tool_alias", ")", ":", "data", "=", "self", ".", "_context", "(", "context_name", ")", "aliases", "=", "data", "[", "\"tool_aliases\"", "]", "if", "tool_name", "in", "aliases", ":", "raise", "SuiteError", "(", "\"Tool %r in context %r is already aliased to %r\"", "%", "(", "tool_name", ",", "context_name", ",", "aliases", "[", "tool_name", "]", ")", ")", "self", ".", "_validate_tool", "(", "context_name", ",", "tool_name", ")", "aliases", "[", "tool_name", "]", "=", "tool_alias", "self", ".", "_flush_tools", "(", ")" ]
Register an alias for a specific tool. Note that a tool alias takes precedence over a context prefix/suffix. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to alias. tool_alias (str): Alias to give the tool.
[ "Register", "an", "alias", "for", "a", "specific", "tool", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L255-L272
232,617
nerdvegas/rez
src/rez/suite.py
Suite.unalias_tool
def unalias_tool(self, context_name, tool_name): """Deregister an alias for a specific tool. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to unalias. """ data = self._context(context_name) aliases = data["tool_aliases"] if tool_name in aliases: del aliases[tool_name] self._flush_tools()
python
def unalias_tool(self, context_name, tool_name): """Deregister an alias for a specific tool. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to unalias. """ data = self._context(context_name) aliases = data["tool_aliases"] if tool_name in aliases: del aliases[tool_name] self._flush_tools()
[ "def", "unalias_tool", "(", "self", ",", "context_name", ",", "tool_name", ")", ":", "data", "=", "self", ".", "_context", "(", "context_name", ")", "aliases", "=", "data", "[", "\"tool_aliases\"", "]", "if", "tool_name", "in", "aliases", ":", "del", "aliases", "[", "tool_name", "]", "self", ".", "_flush_tools", "(", ")" ]
Deregister an alias for a specific tool. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to unalias.
[ "Deregister", "an", "alias", "for", "a", "specific", "tool", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L274-L285
232,618
nerdvegas/rez
src/rez/suite.py
Suite.get_tool_filepath
def get_tool_filepath(self, tool_alias): """Given a visible tool alias, return the full path to the executable. Args: tool_alias (str): Tool alias to search for. Returns: (str): Filepath of executable, or None if the tool is not in the suite. May also return None because this suite has not been saved to disk, so a filepath hasn't yet been established. """ tools_dict = self.get_tools() if tool_alias in tools_dict: if self.tools_path is None: return None else: return os.path.join(self.tools_path, tool_alias) else: return None
python
def get_tool_filepath(self, tool_alias): """Given a visible tool alias, return the full path to the executable. Args: tool_alias (str): Tool alias to search for. Returns: (str): Filepath of executable, or None if the tool is not in the suite. May also return None because this suite has not been saved to disk, so a filepath hasn't yet been established. """ tools_dict = self.get_tools() if tool_alias in tools_dict: if self.tools_path is None: return None else: return os.path.join(self.tools_path, tool_alias) else: return None
[ "def", "get_tool_filepath", "(", "self", ",", "tool_alias", ")", ":", "tools_dict", "=", "self", ".", "get_tools", "(", ")", "if", "tool_alias", "in", "tools_dict", ":", "if", "self", ".", "tools_path", "is", "None", ":", "return", "None", "else", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "tools_path", ",", "tool_alias", ")", "else", ":", "return", "None" ]
Given a visible tool alias, return the full path to the executable. Args: tool_alias (str): Tool alias to search for. Returns: (str): Filepath of executable, or None if the tool is not in the suite. May also return None because this suite has not been saved to disk, so a filepath hasn't yet been established.
[ "Given", "a", "visible", "tool", "alias", "return", "the", "full", "path", "to", "the", "executable", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L302-L320
232,619
nerdvegas/rez
src/rez/suite.py
Suite.get_tool_context
def get_tool_context(self, tool_alias): """Given a visible tool alias, return the name of the context it belongs to. Args: tool_alias (str): Tool alias to search for. Returns: (str): Name of the context that exposes a visible instance of this tool alias, or None if the alias is not available. """ tools_dict = self.get_tools() data = tools_dict.get(tool_alias) if data: return data["context_name"] return None
python
def get_tool_context(self, tool_alias): """Given a visible tool alias, return the name of the context it belongs to. Args: tool_alias (str): Tool alias to search for. Returns: (str): Name of the context that exposes a visible instance of this tool alias, or None if the alias is not available. """ tools_dict = self.get_tools() data = tools_dict.get(tool_alias) if data: return data["context_name"] return None
[ "def", "get_tool_context", "(", "self", ",", "tool_alias", ")", ":", "tools_dict", "=", "self", ".", "get_tools", "(", ")", "data", "=", "tools_dict", ".", "get", "(", "tool_alias", ")", "if", "data", ":", "return", "data", "[", "\"context_name\"", "]", "return", "None" ]
Given a visible tool alias, return the name of the context it belongs to. Args: tool_alias (str): Tool alias to search for. Returns: (str): Name of the context that exposes a visible instance of this tool alias, or None if the alias is not available.
[ "Given", "a", "visible", "tool", "alias", "return", "the", "name", "of", "the", "context", "it", "belongs", "to", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L322-L337
232,620
nerdvegas/rez
src/rez/suite.py
Suite.validate
def validate(self): """Validate the suite.""" for context_name in self.context_names: context = self.context(context_name) try: context.validate() except ResolvedContextError as e: raise SuiteError("Error in context %r: %s" % (context_name, str(e)))
python
def validate(self): """Validate the suite.""" for context_name in self.context_names: context = self.context(context_name) try: context.validate() except ResolvedContextError as e: raise SuiteError("Error in context %r: %s" % (context_name, str(e)))
[ "def", "validate", "(", "self", ")", ":", "for", "context_name", "in", "self", ".", "context_names", ":", "context", "=", "self", ".", "context", "(", "context_name", ")", "try", ":", "context", ".", "validate", "(", ")", "except", "ResolvedContextError", "as", "e", ":", "raise", "SuiteError", "(", "\"Error in context %r: %s\"", "%", "(", "context_name", ",", "str", "(", "e", ")", ")", ")" ]
Validate the suite.
[ "Validate", "the", "suite", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L379-L387
232,621
nerdvegas/rez
src/rez/suite.py
Suite.save
def save(self, path, verbose=False): """Save the suite to disk. Args: path (str): Path to save the suite to. If a suite is already saved at `path`, then it will be overwritten. Otherwise, if `path` exists, an error is raised. """ path = os.path.realpath(path) if os.path.exists(path): if self.load_path and self.load_path == path: if verbose: print "saving over previous suite..." for context_name in self.context_names: self.context(context_name) # load before dir deleted shutil.rmtree(path) else: raise SuiteError("Cannot save, path exists: %r" % path) contexts_path = os.path.join(path, "contexts") os.makedirs(contexts_path) # write suite data data = self.to_dict() filepath = os.path.join(path, "suite.yaml") with open(filepath, "w") as f: f.write(dump_yaml(data)) # write contexts for context_name in self.context_names: context = self.context(context_name) context._set_parent_suite(path, context_name) filepath = self._context_path(context_name, path) if verbose: print "writing %r..." % filepath context.save(filepath) # create alias wrappers tools_path = os.path.join(path, "bin") os.makedirs(tools_path) if verbose: print "creating alias wrappers in %r..." % tools_path tools = self.get_tools() for tool_alias, d in tools.iteritems(): tool_name = d["tool_name"] context_name = d["context_name"] data = self._context(context_name) prefix_char = data.get("prefix_char") if verbose: print ("creating %r -> %r (%s context)..." % (tool_alias, tool_name, context_name)) filepath = os.path.join(tools_path, tool_alias) create_forwarding_script(filepath, module="suite", func_name="_FWD__invoke_suite_tool_alias", context_name=context_name, tool_name=tool_name, prefix_char=prefix_char)
python
def save(self, path, verbose=False): """Save the suite to disk. Args: path (str): Path to save the suite to. If a suite is already saved at `path`, then it will be overwritten. Otherwise, if `path` exists, an error is raised. """ path = os.path.realpath(path) if os.path.exists(path): if self.load_path and self.load_path == path: if verbose: print "saving over previous suite..." for context_name in self.context_names: self.context(context_name) # load before dir deleted shutil.rmtree(path) else: raise SuiteError("Cannot save, path exists: %r" % path) contexts_path = os.path.join(path, "contexts") os.makedirs(contexts_path) # write suite data data = self.to_dict() filepath = os.path.join(path, "suite.yaml") with open(filepath, "w") as f: f.write(dump_yaml(data)) # write contexts for context_name in self.context_names: context = self.context(context_name) context._set_parent_suite(path, context_name) filepath = self._context_path(context_name, path) if verbose: print "writing %r..." % filepath context.save(filepath) # create alias wrappers tools_path = os.path.join(path, "bin") os.makedirs(tools_path) if verbose: print "creating alias wrappers in %r..." % tools_path tools = self.get_tools() for tool_alias, d in tools.iteritems(): tool_name = d["tool_name"] context_name = d["context_name"] data = self._context(context_name) prefix_char = data.get("prefix_char") if verbose: print ("creating %r -> %r (%s context)..." % (tool_alias, tool_name, context_name)) filepath = os.path.join(tools_path, tool_alias) create_forwarding_script(filepath, module="suite", func_name="_FWD__invoke_suite_tool_alias", context_name=context_name, tool_name=tool_name, prefix_char=prefix_char)
[ "def", "save", "(", "self", ",", "path", ",", "verbose", "=", "False", ")", ":", "path", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "self", ".", "load_path", "and", "self", ".", "load_path", "==", "path", ":", "if", "verbose", ":", "print", "\"saving over previous suite...\"", "for", "context_name", "in", "self", ".", "context_names", ":", "self", ".", "context", "(", "context_name", ")", "# load before dir deleted", "shutil", ".", "rmtree", "(", "path", ")", "else", ":", "raise", "SuiteError", "(", "\"Cannot save, path exists: %r\"", "%", "path", ")", "contexts_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"contexts\"", ")", "os", ".", "makedirs", "(", "contexts_path", ")", "# write suite data", "data", "=", "self", ".", "to_dict", "(", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"suite.yaml\"", ")", "with", "open", "(", "filepath", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "dump_yaml", "(", "data", ")", ")", "# write contexts", "for", "context_name", "in", "self", ".", "context_names", ":", "context", "=", "self", ".", "context", "(", "context_name", ")", "context", ".", "_set_parent_suite", "(", "path", ",", "context_name", ")", "filepath", "=", "self", ".", "_context_path", "(", "context_name", ",", "path", ")", "if", "verbose", ":", "print", "\"writing %r...\"", "%", "filepath", "context", ".", "save", "(", "filepath", ")", "# create alias wrappers", "tools_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"bin\"", ")", "os", ".", "makedirs", "(", "tools_path", ")", "if", "verbose", ":", "print", "\"creating alias wrappers in %r...\"", "%", "tools_path", "tools", "=", "self", ".", "get_tools", "(", ")", "for", "tool_alias", ",", "d", "in", "tools", ".", "iteritems", "(", ")", ":", "tool_name", "=", "d", "[", "\"tool_name\"", "]", "context_name", "=", "d", "[", "\"context_name\"", "]", "data", "=", "self", ".", "_context", "(", "context_name", ")", "prefix_char", "=", "data", ".", "get", "(", "\"prefix_char\"", ")", "if", "verbose", ":", "print", "(", "\"creating %r -> %r (%s context)...\"", "%", "(", "tool_alias", ",", "tool_name", ",", "context_name", ")", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "tools_path", ",", "tool_alias", ")", "create_forwarding_script", "(", "filepath", ",", "module", "=", "\"suite\"", ",", "func_name", "=", "\"_FWD__invoke_suite_tool_alias\"", ",", "context_name", "=", "context_name", ",", "tool_name", "=", "tool_name", ",", "prefix_char", "=", "prefix_char", ")" ]
Save the suite to disk. Args: path (str): Path to save the suite to. If a suite is already saved at `path`, then it will be overwritten. Otherwise, if `path` exists, an error is raised.
[ "Save", "the", "suite", "to", "disk", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L415-L476
232,622
nerdvegas/rez
src/rez/suite.py
Suite.print_info
def print_info(self, buf=sys.stdout, verbose=False): """Prints a message summarising the contents of the suite.""" _pr = Printer(buf) if not self.contexts: _pr("Suite is empty.") return context_names = sorted(self.contexts.iterkeys()) _pr("Suite contains %d contexts:" % len(context_names)) if not verbose: _pr(' '.join(context_names)) return tools = self.get_tools().values() context_tools = defaultdict(set) context_variants = defaultdict(set) for entry in tools: context_name = entry["context_name"] context_tools[context_name].add(entry["tool_name"]) context_variants[context_name].add(str(entry["variant"])) _pr() rows = [["NAME", "VISIBLE TOOLS", "PATH"], ["----", "-------------", "----"]] for context_name in context_names: context_path = self._context_path(context_name) or '-' ntools = len(context_tools.get(context_name, [])) if ntools: nvariants = len(context_variants[context_name]) short_desc = "%d tools from %d packages" % (ntools, nvariants) else: short_desc = "no tools" rows.append((context_name, short_desc, context_path)) _pr("\n".join(columnise(rows)))
python
def print_info(self, buf=sys.stdout, verbose=False): """Prints a message summarising the contents of the suite.""" _pr = Printer(buf) if not self.contexts: _pr("Suite is empty.") return context_names = sorted(self.contexts.iterkeys()) _pr("Suite contains %d contexts:" % len(context_names)) if not verbose: _pr(' '.join(context_names)) return tools = self.get_tools().values() context_tools = defaultdict(set) context_variants = defaultdict(set) for entry in tools: context_name = entry["context_name"] context_tools[context_name].add(entry["tool_name"]) context_variants[context_name].add(str(entry["variant"])) _pr() rows = [["NAME", "VISIBLE TOOLS", "PATH"], ["----", "-------------", "----"]] for context_name in context_names: context_path = self._context_path(context_name) or '-' ntools = len(context_tools.get(context_name, [])) if ntools: nvariants = len(context_variants[context_name]) short_desc = "%d tools from %d packages" % (ntools, nvariants) else: short_desc = "no tools" rows.append((context_name, short_desc, context_path)) _pr("\n".join(columnise(rows)))
[ "def", "print_info", "(", "self", ",", "buf", "=", "sys", ".", "stdout", ",", "verbose", "=", "False", ")", ":", "_pr", "=", "Printer", "(", "buf", ")", "if", "not", "self", ".", "contexts", ":", "_pr", "(", "\"Suite is empty.\"", ")", "return", "context_names", "=", "sorted", "(", "self", ".", "contexts", ".", "iterkeys", "(", ")", ")", "_pr", "(", "\"Suite contains %d contexts:\"", "%", "len", "(", "context_names", ")", ")", "if", "not", "verbose", ":", "_pr", "(", "' '", ".", "join", "(", "context_names", ")", ")", "return", "tools", "=", "self", ".", "get_tools", "(", ")", ".", "values", "(", ")", "context_tools", "=", "defaultdict", "(", "set", ")", "context_variants", "=", "defaultdict", "(", "set", ")", "for", "entry", "in", "tools", ":", "context_name", "=", "entry", "[", "\"context_name\"", "]", "context_tools", "[", "context_name", "]", ".", "add", "(", "entry", "[", "\"tool_name\"", "]", ")", "context_variants", "[", "context_name", "]", ".", "add", "(", "str", "(", "entry", "[", "\"variant\"", "]", ")", ")", "_pr", "(", ")", "rows", "=", "[", "[", "\"NAME\"", ",", "\"VISIBLE TOOLS\"", ",", "\"PATH\"", "]", ",", "[", "\"----\"", ",", "\"-------------\"", ",", "\"----\"", "]", "]", "for", "context_name", "in", "context_names", ":", "context_path", "=", "self", ".", "_context_path", "(", "context_name", ")", "or", "'-'", "ntools", "=", "len", "(", "context_tools", ".", "get", "(", "context_name", ",", "[", "]", ")", ")", "if", "ntools", ":", "nvariants", "=", "len", "(", "context_variants", "[", "context_name", "]", ")", "short_desc", "=", "\"%d tools from %d packages\"", "%", "(", "ntools", ",", "nvariants", ")", "else", ":", "short_desc", "=", "\"no tools\"", "rows", ".", "append", "(", "(", "context_name", ",", "short_desc", ",", "context_path", ")", ")", "_pr", "(", "\"\\n\"", ".", "join", "(", "columnise", "(", "rows", ")", ")", ")" ]
Prints a message summarising the contents of the suite.
[ "Prints", "a", "message", "summarising", "the", "contents", "of", "the", "suite", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L525-L562
232,623
nerdvegas/rez
src/rez/build_system.py
get_valid_build_systems
def get_valid_build_systems(working_dir, package=None): """Returns the build system classes that could build the source in given dir. Args: working_dir (str): Dir containing the package definition and potentially build files. package (`Package`): Package to be built. This may or may not be needed to determine the build system. For eg, cmake just has to look for a CMakeLists.txt file, whereas the 'build_command' package field must be present for the 'custom' build system type. Returns: List of class: Valid build system class types. """ from rez.plugin_managers import plugin_manager from rez.exceptions import PackageMetadataError try: package = package or get_developer_package(working_dir) except PackageMetadataError: # no package, or bad package pass if package: if getattr(package, "build_command", None) is not None: buildsys_name = "custom" else: buildsys_name = getattr(package, "build_system", None) # package explicitly specifies build system if buildsys_name: cls = plugin_manager.get_plugin_class('build_system', buildsys_name) return [cls] # detect valid build systems clss = [] for buildsys_name in get_buildsys_types(): cls = plugin_manager.get_plugin_class('build_system', buildsys_name) if cls.is_valid_root(working_dir, package=package): clss.append(cls) # Sometimes files for multiple build systems can be present, because one # build system uses another (a 'child' build system) - eg, cmake uses # make. Detect this case and ignore files from the child build system. # child_clss = set(x.child_build_system() for x in clss) clss = list(set(clss) - child_clss) return clss
python
def get_valid_build_systems(working_dir, package=None): """Returns the build system classes that could build the source in given dir. Args: working_dir (str): Dir containing the package definition and potentially build files. package (`Package`): Package to be built. This may or may not be needed to determine the build system. For eg, cmake just has to look for a CMakeLists.txt file, whereas the 'build_command' package field must be present for the 'custom' build system type. Returns: List of class: Valid build system class types. """ from rez.plugin_managers import plugin_manager from rez.exceptions import PackageMetadataError try: package = package or get_developer_package(working_dir) except PackageMetadataError: # no package, or bad package pass if package: if getattr(package, "build_command", None) is not None: buildsys_name = "custom" else: buildsys_name = getattr(package, "build_system", None) # package explicitly specifies build system if buildsys_name: cls = plugin_manager.get_plugin_class('build_system', buildsys_name) return [cls] # detect valid build systems clss = [] for buildsys_name in get_buildsys_types(): cls = plugin_manager.get_plugin_class('build_system', buildsys_name) if cls.is_valid_root(working_dir, package=package): clss.append(cls) # Sometimes files for multiple build systems can be present, because one # build system uses another (a 'child' build system) - eg, cmake uses # make. Detect this case and ignore files from the child build system. # child_clss = set(x.child_build_system() for x in clss) clss = list(set(clss) - child_clss) return clss
[ "def", "get_valid_build_systems", "(", "working_dir", ",", "package", "=", "None", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "from", "rez", ".", "exceptions", "import", "PackageMetadataError", "try", ":", "package", "=", "package", "or", "get_developer_package", "(", "working_dir", ")", "except", "PackageMetadataError", ":", "# no package, or bad package", "pass", "if", "package", ":", "if", "getattr", "(", "package", ",", "\"build_command\"", ",", "None", ")", "is", "not", "None", ":", "buildsys_name", "=", "\"custom\"", "else", ":", "buildsys_name", "=", "getattr", "(", "package", ",", "\"build_system\"", ",", "None", ")", "# package explicitly specifies build system", "if", "buildsys_name", ":", "cls", "=", "plugin_manager", ".", "get_plugin_class", "(", "'build_system'", ",", "buildsys_name", ")", "return", "[", "cls", "]", "# detect valid build systems", "clss", "=", "[", "]", "for", "buildsys_name", "in", "get_buildsys_types", "(", ")", ":", "cls", "=", "plugin_manager", ".", "get_plugin_class", "(", "'build_system'", ",", "buildsys_name", ")", "if", "cls", ".", "is_valid_root", "(", "working_dir", ",", "package", "=", "package", ")", ":", "clss", ".", "append", "(", "cls", ")", "# Sometimes files for multiple build systems can be present, because one", "# build system uses another (a 'child' build system) - eg, cmake uses", "# make. Detect this case and ignore files from the child build system.", "#", "child_clss", "=", "set", "(", "x", ".", "child_build_system", "(", ")", "for", "x", "in", "clss", ")", "clss", "=", "list", "(", "set", "(", "clss", ")", "-", "child_clss", ")", "return", "clss" ]
Returns the build system classes that could build the source in given dir. Args: working_dir (str): Dir containing the package definition and potentially build files. package (`Package`): Package to be built. This may or may not be needed to determine the build system. For eg, cmake just has to look for a CMakeLists.txt file, whereas the 'build_command' package field must be present for the 'custom' build system type. Returns: List of class: Valid build system class types.
[ "Returns", "the", "build", "system", "classes", "that", "could", "build", "the", "source", "in", "given", "dir", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L14-L62
232,624
nerdvegas/rez
src/rez/build_system.py
create_build_system
def create_build_system(working_dir, buildsys_type=None, package=None, opts=None, write_build_scripts=False, verbose=False, build_args=[], child_build_args=[]): """Return a new build system that can build the source in working_dir.""" from rez.plugin_managers import plugin_manager # detect build system if necessary if not buildsys_type: clss = get_valid_build_systems(working_dir, package=package) if not clss: raise BuildSystemError( "No build system is associated with the path %s" % working_dir) if len(clss) != 1: s = ', '.join(x.name() for x in clss) raise BuildSystemError(("Source could be built with one of: %s; " "Please specify a build system") % s) buildsys_type = iter(clss).next().name() # create instance of build system cls_ = plugin_manager.get_plugin_class('build_system', buildsys_type) return cls_(working_dir, opts=opts, package=package, write_build_scripts=write_build_scripts, verbose=verbose, build_args=build_args, child_build_args=child_build_args)
python
def create_build_system(working_dir, buildsys_type=None, package=None, opts=None, write_build_scripts=False, verbose=False, build_args=[], child_build_args=[]): """Return a new build system that can build the source in working_dir.""" from rez.plugin_managers import plugin_manager # detect build system if necessary if not buildsys_type: clss = get_valid_build_systems(working_dir, package=package) if not clss: raise BuildSystemError( "No build system is associated with the path %s" % working_dir) if len(clss) != 1: s = ', '.join(x.name() for x in clss) raise BuildSystemError(("Source could be built with one of: %s; " "Please specify a build system") % s) buildsys_type = iter(clss).next().name() # create instance of build system cls_ = plugin_manager.get_plugin_class('build_system', buildsys_type) return cls_(working_dir, opts=opts, package=package, write_build_scripts=write_build_scripts, verbose=verbose, build_args=build_args, child_build_args=child_build_args)
[ "def", "create_build_system", "(", "working_dir", ",", "buildsys_type", "=", "None", ",", "package", "=", "None", ",", "opts", "=", "None", ",", "write_build_scripts", "=", "False", ",", "verbose", "=", "False", ",", "build_args", "=", "[", "]", ",", "child_build_args", "=", "[", "]", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "# detect build system if necessary", "if", "not", "buildsys_type", ":", "clss", "=", "get_valid_build_systems", "(", "working_dir", ",", "package", "=", "package", ")", "if", "not", "clss", ":", "raise", "BuildSystemError", "(", "\"No build system is associated with the path %s\"", "%", "working_dir", ")", "if", "len", "(", "clss", ")", "!=", "1", ":", "s", "=", "', '", ".", "join", "(", "x", ".", "name", "(", ")", "for", "x", "in", "clss", ")", "raise", "BuildSystemError", "(", "(", "\"Source could be built with one of: %s; \"", "\"Please specify a build system\"", ")", "%", "s", ")", "buildsys_type", "=", "iter", "(", "clss", ")", ".", "next", "(", ")", ".", "name", "(", ")", "# create instance of build system", "cls_", "=", "plugin_manager", ".", "get_plugin_class", "(", "'build_system'", ",", "buildsys_type", ")", "return", "cls_", "(", "working_dir", ",", "opts", "=", "opts", ",", "package", "=", "package", ",", "write_build_scripts", "=", "write_build_scripts", ",", "verbose", "=", "verbose", ",", "build_args", "=", "build_args", ",", "child_build_args", "=", "child_build_args", ")" ]
Return a new build system that can build the source in working_dir.
[ "Return", "a", "new", "build", "system", "that", "can", "build", "the", "source", "in", "working_dir", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L65-L95
232,625
nerdvegas/rez
src/rez/build_system.py
BuildSystem.build
def build(self, context, variant, build_path, install_path, install=False, build_type=BuildType.local): """Implement this method to perform the actual build. Args: context: A ResolvedContext object that the build process must be executed within. variant (`Variant`): The variant being built. build_path: Where to write temporary build files. May be relative to working_dir. install_path (str): The package repository path to install the package to, if installing. If None, defaults to `config.local_packages_path`. install: If True, install the build. build_type: A BuildType (i.e local or central). Returns: A dict containing the following information: - success: Bool indicating if the build was successful. - extra_files: List of created files of interest, not including build targets. A good example is the interpreted context file, usually named 'build.rxt.sh' or similar. These files should be located under build_path. Rez may install them for debugging purposes. - build_env_script: If this instance was created with write_build_scripts as True, then the build should generate a script which, when run by the user, places them in the build environment. """ raise NotImplementedError
python
def build(self, context, variant, build_path, install_path, install=False, build_type=BuildType.local): """Implement this method to perform the actual build. Args: context: A ResolvedContext object that the build process must be executed within. variant (`Variant`): The variant being built. build_path: Where to write temporary build files. May be relative to working_dir. install_path (str): The package repository path to install the package to, if installing. If None, defaults to `config.local_packages_path`. install: If True, install the build. build_type: A BuildType (i.e local or central). Returns: A dict containing the following information: - success: Bool indicating if the build was successful. - extra_files: List of created files of interest, not including build targets. A good example is the interpreted context file, usually named 'build.rxt.sh' or similar. These files should be located under build_path. Rez may install them for debugging purposes. - build_env_script: If this instance was created with write_build_scripts as True, then the build should generate a script which, when run by the user, places them in the build environment. """ raise NotImplementedError
[ "def", "build", "(", "self", ",", "context", ",", "variant", ",", "build_path", ",", "install_path", ",", "install", "=", "False", ",", "build_type", "=", "BuildType", ".", "local", ")", ":", "raise", "NotImplementedError" ]
Implement this method to perform the actual build. Args: context: A ResolvedContext object that the build process must be executed within. variant (`Variant`): The variant being built. build_path: Where to write temporary build files. May be relative to working_dir. install_path (str): The package repository path to install the package to, if installing. If None, defaults to `config.local_packages_path`. install: If True, install the build. build_type: A BuildType (i.e local or central). Returns: A dict containing the following information: - success: Bool indicating if the build was successful. - extra_files: List of created files of interest, not including build targets. A good example is the interpreted context file, usually named 'build.rxt.sh' or similar. These files should be located under build_path. Rez may install them for debugging purposes. - build_env_script: If this instance was created with write_build_scripts as True, then the build should generate a script which, when run by the user, places them in the build environment.
[ "Implement", "this", "method", "to", "perform", "the", "actual", "build", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L167-L195
232,626
nerdvegas/rez
src/rez/build_system.py
BuildSystem.get_standard_vars
def get_standard_vars(cls, context, variant, build_type, install, build_path, install_path=None): """Returns a standard set of environment variables that can be set for the build system to use """ from rez.config import config package = variant.parent variant_requires = map(str, variant.variant_requires) if variant.index is None: variant_subpath = '' else: variant_subpath = variant._non_shortlinked_subpath vars_ = { 'REZ_BUILD_ENV': 1, 'REZ_BUILD_PATH': build_path, 'REZ_BUILD_THREAD_COUNT': package.config.build_thread_count, 'REZ_BUILD_VARIANT_INDEX': variant.index or 0, 'REZ_BUILD_VARIANT_REQUIRES': ' '.join(variant_requires), 'REZ_BUILD_VARIANT_SUBPATH': variant_subpath, 'REZ_BUILD_PROJECT_VERSION': str(package.version), 'REZ_BUILD_PROJECT_NAME': package.name, 'REZ_BUILD_PROJECT_DESCRIPTION': (package.description or '').strip(), 'REZ_BUILD_PROJECT_FILE': package.filepath, 'REZ_BUILD_SOURCE_PATH': os.path.dirname(package.filepath), 'REZ_BUILD_REQUIRES': ' '.join( str(x) for x in context.requested_packages(True) ), 'REZ_BUILD_REQUIRES_UNVERSIONED': ' '.join( x.name for x in context.requested_packages(True) ), 'REZ_BUILD_TYPE': build_type.name, 'REZ_BUILD_INSTALL': 1 if install else 0, } if install_path: vars_['REZ_BUILD_INSTALL_PATH'] = install_path if config.rez_1_environment_variables and \ not config.disable_rez_1_compatibility and \ build_type == BuildType.central: vars_['REZ_IN_REZ_RELEASE'] = 1 return vars_
python
def get_standard_vars(cls, context, variant, build_type, install, build_path, install_path=None): """Returns a standard set of environment variables that can be set for the build system to use """ from rez.config import config package = variant.parent variant_requires = map(str, variant.variant_requires) if variant.index is None: variant_subpath = '' else: variant_subpath = variant._non_shortlinked_subpath vars_ = { 'REZ_BUILD_ENV': 1, 'REZ_BUILD_PATH': build_path, 'REZ_BUILD_THREAD_COUNT': package.config.build_thread_count, 'REZ_BUILD_VARIANT_INDEX': variant.index or 0, 'REZ_BUILD_VARIANT_REQUIRES': ' '.join(variant_requires), 'REZ_BUILD_VARIANT_SUBPATH': variant_subpath, 'REZ_BUILD_PROJECT_VERSION': str(package.version), 'REZ_BUILD_PROJECT_NAME': package.name, 'REZ_BUILD_PROJECT_DESCRIPTION': (package.description or '').strip(), 'REZ_BUILD_PROJECT_FILE': package.filepath, 'REZ_BUILD_SOURCE_PATH': os.path.dirname(package.filepath), 'REZ_BUILD_REQUIRES': ' '.join( str(x) for x in context.requested_packages(True) ), 'REZ_BUILD_REQUIRES_UNVERSIONED': ' '.join( x.name for x in context.requested_packages(True) ), 'REZ_BUILD_TYPE': build_type.name, 'REZ_BUILD_INSTALL': 1 if install else 0, } if install_path: vars_['REZ_BUILD_INSTALL_PATH'] = install_path if config.rez_1_environment_variables and \ not config.disable_rez_1_compatibility and \ build_type == BuildType.central: vars_['REZ_IN_REZ_RELEASE'] = 1 return vars_
[ "def", "get_standard_vars", "(", "cls", ",", "context", ",", "variant", ",", "build_type", ",", "install", ",", "build_path", ",", "install_path", "=", "None", ")", ":", "from", "rez", ".", "config", "import", "config", "package", "=", "variant", ".", "parent", "variant_requires", "=", "map", "(", "str", ",", "variant", ".", "variant_requires", ")", "if", "variant", ".", "index", "is", "None", ":", "variant_subpath", "=", "''", "else", ":", "variant_subpath", "=", "variant", ".", "_non_shortlinked_subpath", "vars_", "=", "{", "'REZ_BUILD_ENV'", ":", "1", ",", "'REZ_BUILD_PATH'", ":", "build_path", ",", "'REZ_BUILD_THREAD_COUNT'", ":", "package", ".", "config", ".", "build_thread_count", ",", "'REZ_BUILD_VARIANT_INDEX'", ":", "variant", ".", "index", "or", "0", ",", "'REZ_BUILD_VARIANT_REQUIRES'", ":", "' '", ".", "join", "(", "variant_requires", ")", ",", "'REZ_BUILD_VARIANT_SUBPATH'", ":", "variant_subpath", ",", "'REZ_BUILD_PROJECT_VERSION'", ":", "str", "(", "package", ".", "version", ")", ",", "'REZ_BUILD_PROJECT_NAME'", ":", "package", ".", "name", ",", "'REZ_BUILD_PROJECT_DESCRIPTION'", ":", "(", "package", ".", "description", "or", "''", ")", ".", "strip", "(", ")", ",", "'REZ_BUILD_PROJECT_FILE'", ":", "package", ".", "filepath", ",", "'REZ_BUILD_SOURCE_PATH'", ":", "os", ".", "path", ".", "dirname", "(", "package", ".", "filepath", ")", ",", "'REZ_BUILD_REQUIRES'", ":", "' '", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "context", ".", "requested_packages", "(", "True", ")", ")", ",", "'REZ_BUILD_REQUIRES_UNVERSIONED'", ":", "' '", ".", "join", "(", "x", ".", "name", "for", "x", "in", "context", ".", "requested_packages", "(", "True", ")", ")", ",", "'REZ_BUILD_TYPE'", ":", "build_type", ".", "name", ",", "'REZ_BUILD_INSTALL'", ":", "1", "if", "install", "else", "0", ",", "}", "if", "install_path", ":", "vars_", "[", "'REZ_BUILD_INSTALL_PATH'", "]", "=", "install_path", "if", "config", ".", "rez_1_environment_variables", "and", "not", "config", ".", "disable_rez_1_compatibility", "and", "build_type", "==", "BuildType", ".", "central", ":", "vars_", "[", "'REZ_IN_REZ_RELEASE'", "]", "=", "1", "return", "vars_" ]
Returns a standard set of environment variables that can be set for the build system to use
[ "Returns", "a", "standard", "set", "of", "environment", "variables", "that", "can", "be", "set", "for", "the", "build", "system", "to", "use" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L198-L243
232,627
nerdvegas/rez
src/rez/build_system.py
BuildSystem.set_standard_vars
def set_standard_vars(cls, executor, context, variant, build_type, install, build_path, install_path=None): """Sets a standard set of environment variables for the build system to use """ vars = cls.get_standard_vars(context=context, variant=variant, build_type=build_type, install=install, build_path=build_path, install_path=install_path) for var, value in vars.iteritems(): executor.env[var] = value
python
def set_standard_vars(cls, executor, context, variant, build_type, install, build_path, install_path=None): """Sets a standard set of environment variables for the build system to use """ vars = cls.get_standard_vars(context=context, variant=variant, build_type=build_type, install=install, build_path=build_path, install_path=install_path) for var, value in vars.iteritems(): executor.env[var] = value
[ "def", "set_standard_vars", "(", "cls", ",", "executor", ",", "context", ",", "variant", ",", "build_type", ",", "install", ",", "build_path", ",", "install_path", "=", "None", ")", ":", "vars", "=", "cls", ".", "get_standard_vars", "(", "context", "=", "context", ",", "variant", "=", "variant", ",", "build_type", "=", "build_type", ",", "install", "=", "install", ",", "build_path", "=", "build_path", ",", "install_path", "=", "install_path", ")", "for", "var", ",", "value", "in", "vars", ".", "iteritems", "(", ")", ":", "executor", ".", "env", "[", "var", "]", "=", "value" ]
Sets a standard set of environment variables for the build system to use
[ "Sets", "a", "standard", "set", "of", "environment", "variables", "for", "the", "build", "system", "to", "use" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L246-L259
232,628
nerdvegas/rez
src/rez/pip.py
run_pip_command
def run_pip_command(command_args, pip_version=None, python_version=None): """Run a pip command. Args: command_args (list of str): Args to pip. Returns: `subprocess.Popen`: Pip process. """ pip_exe, context = find_pip(pip_version, python_version) command = [pip_exe] + list(command_args) if context is None: return popen(command) else: return context.execute_shell(command=command, block=False)
python
def run_pip_command(command_args, pip_version=None, python_version=None): """Run a pip command. Args: command_args (list of str): Args to pip. Returns: `subprocess.Popen`: Pip process. """ pip_exe, context = find_pip(pip_version, python_version) command = [pip_exe] + list(command_args) if context is None: return popen(command) else: return context.execute_shell(command=command, block=False)
[ "def", "run_pip_command", "(", "command_args", ",", "pip_version", "=", "None", ",", "python_version", "=", "None", ")", ":", "pip_exe", ",", "context", "=", "find_pip", "(", "pip_version", ",", "python_version", ")", "command", "=", "[", "pip_exe", "]", "+", "list", "(", "command_args", ")", "if", "context", "is", "None", ":", "return", "popen", "(", "command", ")", "else", ":", "return", "context", ".", "execute_shell", "(", "command", "=", "command", ",", "block", "=", "False", ")" ]
Run a pip command. Args: command_args (list of str): Args to pip. Returns: `subprocess.Popen`: Pip process.
[ "Run", "a", "pip", "command", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/pip.py#L88-L103
232,629
nerdvegas/rez
src/rez/pip.py
find_pip
def find_pip(pip_version=None, python_version=None): """Find a pip exe using the given python version. Returns: 2-tuple: str: pip executable; `ResolvedContext`: Context containing pip, or None if we fell back to system pip. """ pip_exe = "pip" try: context = create_context(pip_version, python_version) except BuildError as e: # fall back on system pip. Not ideal but at least it's something from rez.backport.shutilwhich import which pip_exe = which("pip") if pip_exe: print_warning( "pip rez package could not be found; system 'pip' command (%s) " "will be used instead." % pip_exe) context = None else: raise e return pip_exe, context
python
def find_pip(pip_version=None, python_version=None): """Find a pip exe using the given python version. Returns: 2-tuple: str: pip executable; `ResolvedContext`: Context containing pip, or None if we fell back to system pip. """ pip_exe = "pip" try: context = create_context(pip_version, python_version) except BuildError as e: # fall back on system pip. Not ideal but at least it's something from rez.backport.shutilwhich import which pip_exe = which("pip") if pip_exe: print_warning( "pip rez package could not be found; system 'pip' command (%s) " "will be used instead." % pip_exe) context = None else: raise e return pip_exe, context
[ "def", "find_pip", "(", "pip_version", "=", "None", ",", "python_version", "=", "None", ")", ":", "pip_exe", "=", "\"pip\"", "try", ":", "context", "=", "create_context", "(", "pip_version", ",", "python_version", ")", "except", "BuildError", "as", "e", ":", "# fall back on system pip. Not ideal but at least it's something", "from", "rez", ".", "backport", ".", "shutilwhich", "import", "which", "pip_exe", "=", "which", "(", "\"pip\"", ")", "if", "pip_exe", ":", "print_warning", "(", "\"pip rez package could not be found; system 'pip' command (%s) \"", "\"will be used instead.\"", "%", "pip_exe", ")", "context", "=", "None", "else", ":", "raise", "e", "return", "pip_exe", ",", "context" ]
Find a pip exe using the given python version. Returns: 2-tuple: str: pip executable; `ResolvedContext`: Context containing pip, or None if we fell back to system pip.
[ "Find", "a", "pip", "exe", "using", "the", "given", "python", "version", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/pip.py#L106-L133
232,630
nerdvegas/rez
src/rez/pip.py
create_context
def create_context(pip_version=None, python_version=None): """Create a context containing the specific pip and python. Args: pip_version (str or `Version`): Version of pip to use, or latest if None. python_version (str or `Version`): Python version to use, or latest if None. Returns: `ResolvedContext`: Context containing pip and python. """ # determine pip pkg to use for install, and python variants to install on if pip_version: pip_req = "pip-%s" % str(pip_version) else: pip_req = "pip" if python_version: ver = Version(str(python_version)) major_minor_ver = ver.trim(2) py_req = "python-%s" % str(major_minor_ver) else: # use latest major.minor package = get_latest_package("python") if package: major_minor_ver = package.version.trim(2) else: # no python package. We're gonna fail, let's just choose current # python version (and fail at context creation time) major_minor_ver = '.'.join(map(str, sys.version_info[:2])) py_req = "python-%s" % str(major_minor_ver) # use pip + latest python to perform pip download operations request = [pip_req, py_req] with convert_errors(from_=(PackageFamilyNotFoundError, PackageNotFoundError), to=BuildError, msg="Cannot run - pip or python rez " "package is not present"): context = ResolvedContext(request) # print pip package used to perform the install pip_variant = context.get_resolved_package("pip") pip_package = pip_variant.parent print_info("Using %s (%s)" % (pip_package.qualified_name, pip_variant.uri)) return context
python
def create_context(pip_version=None, python_version=None): """Create a context containing the specific pip and python. Args: pip_version (str or `Version`): Version of pip to use, or latest if None. python_version (str or `Version`): Python version to use, or latest if None. Returns: `ResolvedContext`: Context containing pip and python. """ # determine pip pkg to use for install, and python variants to install on if pip_version: pip_req = "pip-%s" % str(pip_version) else: pip_req = "pip" if python_version: ver = Version(str(python_version)) major_minor_ver = ver.trim(2) py_req = "python-%s" % str(major_minor_ver) else: # use latest major.minor package = get_latest_package("python") if package: major_minor_ver = package.version.trim(2) else: # no python package. We're gonna fail, let's just choose current # python version (and fail at context creation time) major_minor_ver = '.'.join(map(str, sys.version_info[:2])) py_req = "python-%s" % str(major_minor_ver) # use pip + latest python to perform pip download operations request = [pip_req, py_req] with convert_errors(from_=(PackageFamilyNotFoundError, PackageNotFoundError), to=BuildError, msg="Cannot run - pip or python rez " "package is not present"): context = ResolvedContext(request) # print pip package used to perform the install pip_variant = context.get_resolved_package("pip") pip_package = pip_variant.parent print_info("Using %s (%s)" % (pip_package.qualified_name, pip_variant.uri)) return context
[ "def", "create_context", "(", "pip_version", "=", "None", ",", "python_version", "=", "None", ")", ":", "# determine pip pkg to use for install, and python variants to install on", "if", "pip_version", ":", "pip_req", "=", "\"pip-%s\"", "%", "str", "(", "pip_version", ")", "else", ":", "pip_req", "=", "\"pip\"", "if", "python_version", ":", "ver", "=", "Version", "(", "str", "(", "python_version", ")", ")", "major_minor_ver", "=", "ver", ".", "trim", "(", "2", ")", "py_req", "=", "\"python-%s\"", "%", "str", "(", "major_minor_ver", ")", "else", ":", "# use latest major.minor", "package", "=", "get_latest_package", "(", "\"python\"", ")", "if", "package", ":", "major_minor_ver", "=", "package", ".", "version", ".", "trim", "(", "2", ")", "else", ":", "# no python package. We're gonna fail, let's just choose current", "# python version (and fail at context creation time)", "major_minor_ver", "=", "'.'", ".", "join", "(", "map", "(", "str", ",", "sys", ".", "version_info", "[", ":", "2", "]", ")", ")", "py_req", "=", "\"python-%s\"", "%", "str", "(", "major_minor_ver", ")", "# use pip + latest python to perform pip download operations", "request", "=", "[", "pip_req", ",", "py_req", "]", "with", "convert_errors", "(", "from_", "=", "(", "PackageFamilyNotFoundError", ",", "PackageNotFoundError", ")", ",", "to", "=", "BuildError", ",", "msg", "=", "\"Cannot run - pip or python rez \"", "\"package is not present\"", ")", ":", "context", "=", "ResolvedContext", "(", "request", ")", "# print pip package used to perform the install", "pip_variant", "=", "context", ".", "get_resolved_package", "(", "\"pip\"", ")", "pip_package", "=", "pip_variant", ".", "parent", "print_info", "(", "\"Using %s (%s)\"", "%", "(", "pip_package", ".", "qualified_name", ",", "pip_variant", ".", "uri", ")", ")", "return", "context" ]
Create a context containing the specific pip and python. Args: pip_version (str or `Version`): Version of pip to use, or latest if None. python_version (str or `Version`): Python version to use, or latest if None. Returns: `ResolvedContext`: Context containing pip and python.
[ "Create", "a", "context", "containing", "the", "specific", "pip", "and", "python", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/pip.py#L136-L182
232,631
nerdvegas/rez
src/rez/utils/backcompat.py
convert_old_variant_handle
def convert_old_variant_handle(handle_dict): """Convert a variant handle from serialize_version < 4.0.""" old_variables = handle_dict.get("variables", {}) variables = dict(repository_type="filesystem") for old_key, key in variant_key_conversions.iteritems(): value = old_variables.get(old_key) #if value is not None: variables[key] = value path = handle_dict["path"] filename = os.path.basename(path) if os.path.splitext(filename)[0] == "package": key = "filesystem.variant" else: key = "filesystem.variant.combined" return dict(key=key, variables=variables)
python
def convert_old_variant_handle(handle_dict): """Convert a variant handle from serialize_version < 4.0.""" old_variables = handle_dict.get("variables", {}) variables = dict(repository_type="filesystem") for old_key, key in variant_key_conversions.iteritems(): value = old_variables.get(old_key) #if value is not None: variables[key] = value path = handle_dict["path"] filename = os.path.basename(path) if os.path.splitext(filename)[0] == "package": key = "filesystem.variant" else: key = "filesystem.variant.combined" return dict(key=key, variables=variables)
[ "def", "convert_old_variant_handle", "(", "handle_dict", ")", ":", "old_variables", "=", "handle_dict", ".", "get", "(", "\"variables\"", ",", "{", "}", ")", "variables", "=", "dict", "(", "repository_type", "=", "\"filesystem\"", ")", "for", "old_key", ",", "key", "in", "variant_key_conversions", ".", "iteritems", "(", ")", ":", "value", "=", "old_variables", ".", "get", "(", "old_key", ")", "#if value is not None:", "variables", "[", "key", "]", "=", "value", "path", "=", "handle_dict", "[", "\"path\"", "]", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "==", "\"package\"", ":", "key", "=", "\"filesystem.variant\"", "else", ":", "key", "=", "\"filesystem.variant.combined\"", "return", "dict", "(", "key", "=", "key", ",", "variables", "=", "variables", ")" ]
Convert a variant handle from serialize_version < 4.0.
[ "Convert", "a", "variant", "handle", "from", "serialize_version", "<", "4", ".", "0", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/backcompat.py#L20-L37
232,632
nerdvegas/rez
src/rez/utils/py_dist.py
convert_requirement
def convert_requirement(req): """ Converts a pkg_resources.Requirement object into a list of Rez package request strings. """ pkg_name = convert_name(req.project_name) if not req.specs: return [pkg_name] req_strs = [] for spec in req.specs: op, ver = spec ver = convert_version(ver) if op == "<": r = "%s-0+<%s" % (pkg_name, ver) req_strs.append(r) elif op == "<=": r = "%s-0+<%s|%s" % (pkg_name, ver, ver) req_strs.append(r) elif op == "==": r = "%s-%s" % (pkg_name, ver) req_strs.append(r) elif op == ">=": r = "%s-%s+" % (pkg_name, ver) req_strs.append(r) elif op == ">": r1 = "%s-%s+" % (pkg_name, ver) r2 = "!%s-%s" % (pkg_name, ver) req_strs.append(r1) req_strs.append(r2) elif op == "!=": r = "!%s-%s" % (pkg_name, ver) req_strs.append(r) else: print >> sys.stderr, \ "Warning: Can't understand op '%s', just depending on unversioned package..." % op req_strs.append(pkg_name) return req_strs
python
def convert_requirement(req): """ Converts a pkg_resources.Requirement object into a list of Rez package request strings. """ pkg_name = convert_name(req.project_name) if not req.specs: return [pkg_name] req_strs = [] for spec in req.specs: op, ver = spec ver = convert_version(ver) if op == "<": r = "%s-0+<%s" % (pkg_name, ver) req_strs.append(r) elif op == "<=": r = "%s-0+<%s|%s" % (pkg_name, ver, ver) req_strs.append(r) elif op == "==": r = "%s-%s" % (pkg_name, ver) req_strs.append(r) elif op == ">=": r = "%s-%s+" % (pkg_name, ver) req_strs.append(r) elif op == ">": r1 = "%s-%s+" % (pkg_name, ver) r2 = "!%s-%s" % (pkg_name, ver) req_strs.append(r1) req_strs.append(r2) elif op == "!=": r = "!%s-%s" % (pkg_name, ver) req_strs.append(r) else: print >> sys.stderr, \ "Warning: Can't understand op '%s', just depending on unversioned package..." % op req_strs.append(pkg_name) return req_strs
[ "def", "convert_requirement", "(", "req", ")", ":", "pkg_name", "=", "convert_name", "(", "req", ".", "project_name", ")", "if", "not", "req", ".", "specs", ":", "return", "[", "pkg_name", "]", "req_strs", "=", "[", "]", "for", "spec", "in", "req", ".", "specs", ":", "op", ",", "ver", "=", "spec", "ver", "=", "convert_version", "(", "ver", ")", "if", "op", "==", "\"<\"", ":", "r", "=", "\"%s-0+<%s\"", "%", "(", "pkg_name", ",", "ver", ")", "req_strs", ".", "append", "(", "r", ")", "elif", "op", "==", "\"<=\"", ":", "r", "=", "\"%s-0+<%s|%s\"", "%", "(", "pkg_name", ",", "ver", ",", "ver", ")", "req_strs", ".", "append", "(", "r", ")", "elif", "op", "==", "\"==\"", ":", "r", "=", "\"%s-%s\"", "%", "(", "pkg_name", ",", "ver", ")", "req_strs", ".", "append", "(", "r", ")", "elif", "op", "==", "\">=\"", ":", "r", "=", "\"%s-%s+\"", "%", "(", "pkg_name", ",", "ver", ")", "req_strs", ".", "append", "(", "r", ")", "elif", "op", "==", "\">\"", ":", "r1", "=", "\"%s-%s+\"", "%", "(", "pkg_name", ",", "ver", ")", "r2", "=", "\"!%s-%s\"", "%", "(", "pkg_name", ",", "ver", ")", "req_strs", ".", "append", "(", "r1", ")", "req_strs", ".", "append", "(", "r2", ")", "elif", "op", "==", "\"!=\"", ":", "r", "=", "\"!%s-%s\"", "%", "(", "pkg_name", ",", "ver", ")", "req_strs", ".", "append", "(", "r", ")", "else", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Warning: Can't understand op '%s', just depending on unversioned package...\"", "%", "op", "req_strs", ".", "append", "(", "pkg_name", ")", "return", "req_strs" ]
Converts a pkg_resources.Requirement object into a list of Rez package request strings.
[ "Converts", "a", "pkg_resources", ".", "Requirement", "object", "into", "a", "list", "of", "Rez", "package", "request", "strings", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/py_dist.py#L42-L80
232,633
nerdvegas/rez
src/rez/utils/py_dist.py
get_dist_dependencies
def get_dist_dependencies(name, recurse=True): """ Get the dependencies of the given, already installed distribution. @param recurse If True, recursively find all dependencies. @returns A set of package names. @note The first entry in the list is always the top-level package itself. """ dist = pkg_resources.get_distribution(name) pkg_name = convert_name(dist.project_name) reqs = set() working = set([dist]) depth = 0 while working: deps = set() for distname in working: dist = pkg_resources.get_distribution(distname) pkg_name = convert_name(dist.project_name) reqs.add(pkg_name) for req in dist.requires(): reqs_ = convert_requirement(req) deps |= set(x.split('-', 1)[0] for x in reqs_ if not x.startswith('!')) working = deps - reqs depth += 1 if (not recurse) and (depth >= 2): break return reqs
python
def get_dist_dependencies(name, recurse=True): """ Get the dependencies of the given, already installed distribution. @param recurse If True, recursively find all dependencies. @returns A set of package names. @note The first entry in the list is always the top-level package itself. """ dist = pkg_resources.get_distribution(name) pkg_name = convert_name(dist.project_name) reqs = set() working = set([dist]) depth = 0 while working: deps = set() for distname in working: dist = pkg_resources.get_distribution(distname) pkg_name = convert_name(dist.project_name) reqs.add(pkg_name) for req in dist.requires(): reqs_ = convert_requirement(req) deps |= set(x.split('-', 1)[0] for x in reqs_ if not x.startswith('!')) working = deps - reqs depth += 1 if (not recurse) and (depth >= 2): break return reqs
[ "def", "get_dist_dependencies", "(", "name", ",", "recurse", "=", "True", ")", ":", "dist", "=", "pkg_resources", ".", "get_distribution", "(", "name", ")", "pkg_name", "=", "convert_name", "(", "dist", ".", "project_name", ")", "reqs", "=", "set", "(", ")", "working", "=", "set", "(", "[", "dist", "]", ")", "depth", "=", "0", "while", "working", ":", "deps", "=", "set", "(", ")", "for", "distname", "in", "working", ":", "dist", "=", "pkg_resources", ".", "get_distribution", "(", "distname", ")", "pkg_name", "=", "convert_name", "(", "dist", ".", "project_name", ")", "reqs", ".", "add", "(", "pkg_name", ")", "for", "req", "in", "dist", ".", "requires", "(", ")", ":", "reqs_", "=", "convert_requirement", "(", "req", ")", "deps", "|=", "set", "(", "x", ".", "split", "(", "'-'", ",", "1", ")", "[", "0", "]", "for", "x", "in", "reqs_", "if", "not", "x", ".", "startswith", "(", "'!'", ")", ")", "working", "=", "deps", "-", "reqs", "depth", "+=", "1", "if", "(", "not", "recurse", ")", "and", "(", "depth", ">=", "2", ")", ":", "break", "return", "reqs" ]
Get the dependencies of the given, already installed distribution. @param recurse If True, recursively find all dependencies. @returns A set of package names. @note The first entry in the list is always the top-level package itself.
[ "Get", "the", "dependencies", "of", "the", "given", "already", "installed", "distribution", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/py_dist.py#L83-L114
232,634
nerdvegas/rez
src/rez/vendor/pygraph/mixins/common.py
common.add_graph
def add_graph(self, other): """ Add other graph to this graph. @attention: Attributes and labels are not preserved. @type other: graph @param other: Graph """ self.add_nodes( n for n in other.nodes() if not n in self.nodes() ) for each_node in other.nodes(): for each_edge in other.neighbors(each_node): if (not self.has_edge((each_node, each_edge))): self.add_edge((each_node, each_edge))
python
def add_graph(self, other): """ Add other graph to this graph. @attention: Attributes and labels are not preserved. @type other: graph @param other: Graph """ self.add_nodes( n for n in other.nodes() if not n in self.nodes() ) for each_node in other.nodes(): for each_edge in other.neighbors(each_node): if (not self.has_edge((each_node, each_edge))): self.add_edge((each_node, each_edge))
[ "def", "add_graph", "(", "self", ",", "other", ")", ":", "self", ".", "add_nodes", "(", "n", "for", "n", "in", "other", ".", "nodes", "(", ")", "if", "not", "n", "in", "self", ".", "nodes", "(", ")", ")", "for", "each_node", "in", "other", ".", "nodes", "(", ")", ":", "for", "each_edge", "in", "other", ".", "neighbors", "(", "each_node", ")", ":", "if", "(", "not", "self", ".", "has_edge", "(", "(", "each_node", ",", "each_edge", ")", ")", ")", ":", "self", ".", "add_edge", "(", "(", "each_node", ",", "each_edge", ")", ")" ]
Add other graph to this graph. @attention: Attributes and labels are not preserved. @type other: graph @param other: Graph
[ "Add", "other", "graph", "to", "this", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L107-L121
232,635
nerdvegas/rez
src/rez/vendor/pygraph/mixins/common.py
common.add_spanning_tree
def add_spanning_tree(self, st): """ Add a spanning tree to the graph. @type st: dictionary @param st: Spanning tree. """ self.add_nodes(list(st.keys())) for each in st: if (st[each] is not None): self.add_edge((st[each], each))
python
def add_spanning_tree(self, st): """ Add a spanning tree to the graph. @type st: dictionary @param st: Spanning tree. """ self.add_nodes(list(st.keys())) for each in st: if (st[each] is not None): self.add_edge((st[each], each))
[ "def", "add_spanning_tree", "(", "self", ",", "st", ")", ":", "self", ".", "add_nodes", "(", "list", "(", "st", ".", "keys", "(", ")", ")", ")", "for", "each", "in", "st", ":", "if", "(", "st", "[", "each", "]", "is", "not", "None", ")", ":", "self", ".", "add_edge", "(", "(", "st", "[", "each", "]", ",", "each", ")", ")" ]
Add a spanning tree to the graph. @type st: dictionary @param st: Spanning tree.
[ "Add", "a", "spanning", "tree", "to", "the", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L124-L134
232,636
nerdvegas/rez
src/rez/vendor/pygraph/mixins/common.py
common.complete
def complete(self): """ Make the graph a complete graph. @attention: This will modify the current graph. """ for each in self.nodes(): for other in self.nodes(): if (each != other and not self.has_edge((each, other))): self.add_edge((each, other))
python
def complete(self): """ Make the graph a complete graph. @attention: This will modify the current graph. """ for each in self.nodes(): for other in self.nodes(): if (each != other and not self.has_edge((each, other))): self.add_edge((each, other))
[ "def", "complete", "(", "self", ")", ":", "for", "each", "in", "self", ".", "nodes", "(", ")", ":", "for", "other", "in", "self", ".", "nodes", "(", ")", ":", "if", "(", "each", "!=", "other", "and", "not", "self", ".", "has_edge", "(", "(", "each", ",", "other", ")", ")", ")", ":", "self", ".", "add_edge", "(", "(", "each", ",", "other", ")", ")" ]
Make the graph a complete graph. @attention: This will modify the current graph.
[ "Make", "the", "graph", "a", "complete", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L137-L146
232,637
nerdvegas/rez
src/rez/vendor/pygraph/mixins/common.py
common.inverse
def inverse(self): """ Return the inverse of the graph. @rtype: graph @return: Complement graph for the graph. """ inv = self.__class__() inv.add_nodes(self.nodes()) inv.complete() for each in self.edges(): if (inv.has_edge(each)): inv.del_edge(each) return inv
python
def inverse(self): """ Return the inverse of the graph. @rtype: graph @return: Complement graph for the graph. """ inv = self.__class__() inv.add_nodes(self.nodes()) inv.complete() for each in self.edges(): if (inv.has_edge(each)): inv.del_edge(each) return inv
[ "def", "inverse", "(", "self", ")", ":", "inv", "=", "self", ".", "__class__", "(", ")", "inv", ".", "add_nodes", "(", "self", ".", "nodes", "(", ")", ")", "inv", ".", "complete", "(", ")", "for", "each", "in", "self", ".", "edges", "(", ")", ":", "if", "(", "inv", ".", "has_edge", "(", "each", ")", ")", ":", "inv", ".", "del_edge", "(", "each", ")", "return", "inv" ]
Return the inverse of the graph. @rtype: graph @return: Complement graph for the graph.
[ "Return", "the", "inverse", "of", "the", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L149-L162
232,638
nerdvegas/rez
src/rez/vendor/pygraph/mixins/common.py
common.reverse
def reverse(self): """ Generate the reverse of a directed graph, returns an identical graph if not directed. Attributes & weights are preserved. @rtype: digraph @return: The directed graph that should be reversed. """ assert self.DIRECTED, "Undirected graph types such as %s cannot be reversed" % self.__class__.__name__ N = self.__class__() #- Add the nodes N.add_nodes( n for n in self.nodes() ) #- Add the reversed edges for (u, v) in self.edges(): wt = self.edge_weight((u, v)) label = self.edge_label((u, v)) attributes = self.edge_attributes((u, v)) N.add_edge((v, u), wt, label, attributes) return N
python
def reverse(self): """ Generate the reverse of a directed graph, returns an identical graph if not directed. Attributes & weights are preserved. @rtype: digraph @return: The directed graph that should be reversed. """ assert self.DIRECTED, "Undirected graph types such as %s cannot be reversed" % self.__class__.__name__ N = self.__class__() #- Add the nodes N.add_nodes( n for n in self.nodes() ) #- Add the reversed edges for (u, v) in self.edges(): wt = self.edge_weight((u, v)) label = self.edge_label((u, v)) attributes = self.edge_attributes((u, v)) N.add_edge((v, u), wt, label, attributes) return N
[ "def", "reverse", "(", "self", ")", ":", "assert", "self", ".", "DIRECTED", ",", "\"Undirected graph types such as %s cannot be reversed\"", "%", "self", ".", "__class__", ".", "__name__", "N", "=", "self", ".", "__class__", "(", ")", "#- Add the nodes", "N", ".", "add_nodes", "(", "n", "for", "n", "in", "self", ".", "nodes", "(", ")", ")", "#- Add the reversed edges", "for", "(", "u", ",", "v", ")", "in", "self", ".", "edges", "(", ")", ":", "wt", "=", "self", ".", "edge_weight", "(", "(", "u", ",", "v", ")", ")", "label", "=", "self", ".", "edge_label", "(", "(", "u", ",", "v", ")", ")", "attributes", "=", "self", ".", "edge_attributes", "(", "(", "u", ",", "v", ")", ")", "N", ".", "add_edge", "(", "(", "v", ",", "u", ")", ",", "wt", ",", "label", ",", "attributes", ")", "return", "N" ]
Generate the reverse of a directed graph, returns an identical graph if not directed. Attributes & weights are preserved. @rtype: digraph @return: The directed graph that should be reversed.
[ "Generate", "the", "reverse", "of", "a", "directed", "graph", "returns", "an", "identical", "graph", "if", "not", "directed", ".", "Attributes", "&", "weights", "are", "preserved", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L164-L185
232,639
nerdvegas/rez
src/rez/resolved_context.py
get_lock_request
def get_lock_request(name, version, patch_lock, weak=True): """Given a package and patch lock, return the equivalent request. For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent request is '~foo-1.2'. This restricts updates to foo to patch-or-lower version changes only. For objects not versioned down to a given lock level, the closest possible lock is applied. So 'lock_3' applied to 'foo-1' would give '~foo-1'. Args: name (str): Package name. version (Version): Package version. patch_lock (PatchLock): Lock type to apply. Returns: `PackageRequest` object, or None if there is no equivalent request. """ ch = '~' if weak else '' if patch_lock == PatchLock.lock: s = "%s%s==%s" % (ch, name, str(version)) return PackageRequest(s) elif (patch_lock == PatchLock.no_lock) or (not version): return None version_ = version.trim(patch_lock.rank) s = "%s%s-%s" % (ch, name, str(version_)) return PackageRequest(s)
python
def get_lock_request(name, version, patch_lock, weak=True): """Given a package and patch lock, return the equivalent request. For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent request is '~foo-1.2'. This restricts updates to foo to patch-or-lower version changes only. For objects not versioned down to a given lock level, the closest possible lock is applied. So 'lock_3' applied to 'foo-1' would give '~foo-1'. Args: name (str): Package name. version (Version): Package version. patch_lock (PatchLock): Lock type to apply. Returns: `PackageRequest` object, or None if there is no equivalent request. """ ch = '~' if weak else '' if patch_lock == PatchLock.lock: s = "%s%s==%s" % (ch, name, str(version)) return PackageRequest(s) elif (patch_lock == PatchLock.no_lock) or (not version): return None version_ = version.trim(patch_lock.rank) s = "%s%s-%s" % (ch, name, str(version_)) return PackageRequest(s)
[ "def", "get_lock_request", "(", "name", ",", "version", ",", "patch_lock", ",", "weak", "=", "True", ")", ":", "ch", "=", "'~'", "if", "weak", "else", "''", "if", "patch_lock", "==", "PatchLock", ".", "lock", ":", "s", "=", "\"%s%s==%s\"", "%", "(", "ch", ",", "name", ",", "str", "(", "version", ")", ")", "return", "PackageRequest", "(", "s", ")", "elif", "(", "patch_lock", "==", "PatchLock", ".", "no_lock", ")", "or", "(", "not", "version", ")", ":", "return", "None", "version_", "=", "version", ".", "trim", "(", "patch_lock", ".", "rank", ")", "s", "=", "\"%s%s-%s\"", "%", "(", "ch", ",", "name", ",", "str", "(", "version_", ")", ")", "return", "PackageRequest", "(", "s", ")" ]
Given a package and patch lock, return the equivalent request. For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent request is '~foo-1.2'. This restricts updates to foo to patch-or-lower version changes only. For objects not versioned down to a given lock level, the closest possible lock is applied. So 'lock_3' applied to 'foo-1' would give '~foo-1'. Args: name (str): Package name. version (Version): Package version. patch_lock (PatchLock): Lock type to apply. Returns: `PackageRequest` object, or None if there is no equivalent request.
[ "Given", "a", "package", "and", "patch", "lock", "return", "the", "equivalent", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L76-L102
232,640
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.requested_packages
def requested_packages(self, include_implicit=False): """Get packages in the request. Args: include_implicit (bool): If True, implicit packages are appended to the result. Returns: List of `PackageRequest` objects. """ if include_implicit: return self._package_requests + self.implicit_packages else: return self._package_requests
python
def requested_packages(self, include_implicit=False): """Get packages in the request. Args: include_implicit (bool): If True, implicit packages are appended to the result. Returns: List of `PackageRequest` objects. """ if include_implicit: return self._package_requests + self.implicit_packages else: return self._package_requests
[ "def", "requested_packages", "(", "self", ",", "include_implicit", "=", "False", ")", ":", "if", "include_implicit", ":", "return", "self", ".", "_package_requests", "+", "self", ".", "implicit_packages", "else", ":", "return", "self", ".", "_package_requests" ]
Get packages in the request. Args: include_implicit (bool): If True, implicit packages are appended to the result. Returns: List of `PackageRequest` objects.
[ "Get", "packages", "in", "the", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L322-L335
232,641
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_resolved_package
def get_resolved_package(self, name): """Returns a `Variant` object or None if the package is not in the resolve. """ pkgs = [x for x in self._resolved_packages if x.name == name] return pkgs[0] if pkgs else None
python
def get_resolved_package(self, name): """Returns a `Variant` object or None if the package is not in the resolve. """ pkgs = [x for x in self._resolved_packages if x.name == name] return pkgs[0] if pkgs else None
[ "def", "get_resolved_package", "(", "self", ",", "name", ")", ":", "pkgs", "=", "[", "x", "for", "x", "in", "self", ".", "_resolved_packages", "if", "x", ".", "name", "==", "name", "]", "return", "pkgs", "[", "0", "]", "if", "pkgs", "else", "None" ]
Returns a `Variant` object or None if the package is not in the resolve.
[ "Returns", "a", "Variant", "object", "or", "None", "if", "the", "package", "is", "not", "in", "the", "resolve", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L384-L389
232,642
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_patched_request
def get_patched_request(self, package_requests=None, package_subtractions=None, strict=False, rank=0): """Get a 'patched' request. A patched request is a copy of this context's request, but with some changes applied. This can then be used to create a new, 'patched' context. New package requests override original requests based on the type - normal, conflict or weak. So 'foo-2' overrides 'foo-1', '!foo-2' overrides '!foo-1' and '~foo-2' overrides '~foo-1', but a request such as '!foo-2' would not replace 'foo-1' - it would be added instead. Note that requests in `package_requests` can have the form '^foo'. This is another way of supplying package subtractions. Any new requests that don't override original requests are appended, in the order that they appear in `package_requests`. Args: package_requests (list of str or list of `PackageRequest`): Overriding requests. package_subtractions (list of str): Any original request with a package name in this list is removed, before the new requests are added. strict (bool): If True, the current context's resolve is used as the original request list, rather than the request. rank (int): If > 1, package versions can only increase in this rank and further - for example, rank=3 means that only version patch numbers are allowed to increase, major and minor versions will not change. This is only applied to packages that have not been explicitly overridden in `package_requests`. If rank <= 1, or `strict` is True, rank is ignored. Returns: List of `PackageRequest` objects that can be used to construct a new `ResolvedContext` object. """ # assemble source request if strict: request = [] for variant in self.resolved_packages: req = PackageRequest(variant.qualified_package_name) request.append(req) else: request = self.requested_packages()[:] # convert '^foo'-style requests to subtractions if package_requests: package_subtractions = package_subtractions or [] indexes = [] for i, req in enumerate(package_requests): name = str(req) if name.startswith('^'): package_subtractions.append(name[1:]) indexes.append(i) for i in reversed(indexes): del package_requests[i] # apply subtractions if package_subtractions: request = [x for x in request if x.name not in package_subtractions] # apply overrides if package_requests: request_dict = dict((x.name, (i, x)) for i, x in enumerate(request)) request_ = [] for req in package_requests: if isinstance(req, basestring): req = PackageRequest(req) if req.name in request_dict: i, req_ = request_dict[req.name] if (req_ is not None) and (req_.conflict == req.conflict) \ and (req_.weak == req.weak): request[i] = req del request_dict[req.name] else: request_.append(req) else: request_.append(req) request += request_ # add rank limiters if not strict and rank > 1: overrides = set(x.name for x in package_requests if not x.conflict) rank_limiters = [] for variant in self.resolved_packages: if variant.name not in overrides: if len(variant.version) >= rank: version = variant.version.trim(rank - 1) version = version.next() req = "~%s<%s" % (variant.name, str(version)) rank_limiters.append(req) request += rank_limiters return request
python
def get_patched_request(self, package_requests=None, package_subtractions=None, strict=False, rank=0): """Get a 'patched' request. A patched request is a copy of this context's request, but with some changes applied. This can then be used to create a new, 'patched' context. New package requests override original requests based on the type - normal, conflict or weak. So 'foo-2' overrides 'foo-1', '!foo-2' overrides '!foo-1' and '~foo-2' overrides '~foo-1', but a request such as '!foo-2' would not replace 'foo-1' - it would be added instead. Note that requests in `package_requests` can have the form '^foo'. This is another way of supplying package subtractions. Any new requests that don't override original requests are appended, in the order that they appear in `package_requests`. Args: package_requests (list of str or list of `PackageRequest`): Overriding requests. package_subtractions (list of str): Any original request with a package name in this list is removed, before the new requests are added. strict (bool): If True, the current context's resolve is used as the original request list, rather than the request. rank (int): If > 1, package versions can only increase in this rank and further - for example, rank=3 means that only version patch numbers are allowed to increase, major and minor versions will not change. This is only applied to packages that have not been explicitly overridden in `package_requests`. If rank <= 1, or `strict` is True, rank is ignored. Returns: List of `PackageRequest` objects that can be used to construct a new `ResolvedContext` object. """ # assemble source request if strict: request = [] for variant in self.resolved_packages: req = PackageRequest(variant.qualified_package_name) request.append(req) else: request = self.requested_packages()[:] # convert '^foo'-style requests to subtractions if package_requests: package_subtractions = package_subtractions or [] indexes = [] for i, req in enumerate(package_requests): name = str(req) if name.startswith('^'): package_subtractions.append(name[1:]) indexes.append(i) for i in reversed(indexes): del package_requests[i] # apply subtractions if package_subtractions: request = [x for x in request if x.name not in package_subtractions] # apply overrides if package_requests: request_dict = dict((x.name, (i, x)) for i, x in enumerate(request)) request_ = [] for req in package_requests: if isinstance(req, basestring): req = PackageRequest(req) if req.name in request_dict: i, req_ = request_dict[req.name] if (req_ is not None) and (req_.conflict == req.conflict) \ and (req_.weak == req.weak): request[i] = req del request_dict[req.name] else: request_.append(req) else: request_.append(req) request += request_ # add rank limiters if not strict and rank > 1: overrides = set(x.name for x in package_requests if not x.conflict) rank_limiters = [] for variant in self.resolved_packages: if variant.name not in overrides: if len(variant.version) >= rank: version = variant.version.trim(rank - 1) version = version.next() req = "~%s<%s" % (variant.name, str(version)) rank_limiters.append(req) request += rank_limiters return request
[ "def", "get_patched_request", "(", "self", ",", "package_requests", "=", "None", ",", "package_subtractions", "=", "None", ",", "strict", "=", "False", ",", "rank", "=", "0", ")", ":", "# assemble source request", "if", "strict", ":", "request", "=", "[", "]", "for", "variant", "in", "self", ".", "resolved_packages", ":", "req", "=", "PackageRequest", "(", "variant", ".", "qualified_package_name", ")", "request", ".", "append", "(", "req", ")", "else", ":", "request", "=", "self", ".", "requested_packages", "(", ")", "[", ":", "]", "# convert '^foo'-style requests to subtractions", "if", "package_requests", ":", "package_subtractions", "=", "package_subtractions", "or", "[", "]", "indexes", "=", "[", "]", "for", "i", ",", "req", "in", "enumerate", "(", "package_requests", ")", ":", "name", "=", "str", "(", "req", ")", "if", "name", ".", "startswith", "(", "'^'", ")", ":", "package_subtractions", ".", "append", "(", "name", "[", "1", ":", "]", ")", "indexes", ".", "append", "(", "i", ")", "for", "i", "in", "reversed", "(", "indexes", ")", ":", "del", "package_requests", "[", "i", "]", "# apply subtractions", "if", "package_subtractions", ":", "request", "=", "[", "x", "for", "x", "in", "request", "if", "x", ".", "name", "not", "in", "package_subtractions", "]", "# apply overrides", "if", "package_requests", ":", "request_dict", "=", "dict", "(", "(", "x", ".", "name", ",", "(", "i", ",", "x", ")", ")", "for", "i", ",", "x", "in", "enumerate", "(", "request", ")", ")", "request_", "=", "[", "]", "for", "req", "in", "package_requests", ":", "if", "isinstance", "(", "req", ",", "basestring", ")", ":", "req", "=", "PackageRequest", "(", "req", ")", "if", "req", ".", "name", "in", "request_dict", ":", "i", ",", "req_", "=", "request_dict", "[", "req", ".", "name", "]", "if", "(", "req_", "is", "not", "None", ")", "and", "(", "req_", ".", "conflict", "==", "req", ".", "conflict", ")", "and", "(", "req_", ".", "weak", "==", "req", ".", "weak", ")", ":", "request", "[", "i", "]", "=", "req", "del", "request_dict", "[", "req", ".", "name", "]", "else", ":", "request_", ".", "append", "(", "req", ")", "else", ":", "request_", ".", "append", "(", "req", ")", "request", "+=", "request_", "# add rank limiters", "if", "not", "strict", "and", "rank", ">", "1", ":", "overrides", "=", "set", "(", "x", ".", "name", "for", "x", "in", "package_requests", "if", "not", "x", ".", "conflict", ")", "rank_limiters", "=", "[", "]", "for", "variant", "in", "self", ".", "resolved_packages", ":", "if", "variant", ".", "name", "not", "in", "overrides", ":", "if", "len", "(", "variant", ".", "version", ")", ">=", "rank", ":", "version", "=", "variant", ".", "version", ".", "trim", "(", "rank", "-", "1", ")", "version", "=", "version", ".", "next", "(", ")", "req", "=", "\"~%s<%s\"", "%", "(", "variant", ".", "name", ",", "str", "(", "version", ")", ")", "rank_limiters", ".", "append", "(", "req", ")", "request", "+=", "rank_limiters", "return", "request" ]
Get a 'patched' request. A patched request is a copy of this context's request, but with some changes applied. This can then be used to create a new, 'patched' context. New package requests override original requests based on the type - normal, conflict or weak. So 'foo-2' overrides 'foo-1', '!foo-2' overrides '!foo-1' and '~foo-2' overrides '~foo-1', but a request such as '!foo-2' would not replace 'foo-1' - it would be added instead. Note that requests in `package_requests` can have the form '^foo'. This is another way of supplying package subtractions. Any new requests that don't override original requests are appended, in the order that they appear in `package_requests`. Args: package_requests (list of str or list of `PackageRequest`): Overriding requests. package_subtractions (list of str): Any original request with a package name in this list is removed, before the new requests are added. strict (bool): If True, the current context's resolve is used as the original request list, rather than the request. rank (int): If > 1, package versions can only increase in this rank and further - for example, rank=3 means that only version patch numbers are allowed to increase, major and minor versions will not change. This is only applied to packages that have not been explicitly overridden in `package_requests`. If rank <= 1, or `strict` is True, rank is ignored. Returns: List of `PackageRequest` objects that can be used to construct a new `ResolvedContext` object.
[ "Get", "a", "patched", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L397-L495
232,643
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.write_to_buffer
def write_to_buffer(self, buf): """Save the context to a buffer.""" doc = self.to_dict() if config.rxt_as_yaml: content = dump_yaml(doc) else: content = json.dumps(doc, indent=4, separators=(",", ": ")) buf.write(content)
python
def write_to_buffer(self, buf): """Save the context to a buffer.""" doc = self.to_dict() if config.rxt_as_yaml: content = dump_yaml(doc) else: content = json.dumps(doc, indent=4, separators=(",", ": ")) buf.write(content)
[ "def", "write_to_buffer", "(", "self", ",", "buf", ")", ":", "doc", "=", "self", ".", "to_dict", "(", ")", "if", "config", ".", "rxt_as_yaml", ":", "content", "=", "dump_yaml", "(", "doc", ")", "else", ":", "content", "=", "json", ".", "dumps", "(", "doc", ",", "indent", "=", "4", ",", "separators", "=", "(", "\",\"", ",", "\": \"", ")", ")", "buf", ".", "write", "(", "content", ")" ]
Save the context to a buffer.
[ "Save", "the", "context", "to", "a", "buffer", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L533-L542
232,644
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_current
def get_current(cls): """Get the context for the current env, if there is one. Returns: `ResolvedContext`: Current context, or None if not in a resolved env. """ filepath = os.getenv("REZ_RXT_FILE") if not filepath or not os.path.exists(filepath): return None return cls.load(filepath)
python
def get_current(cls): """Get the context for the current env, if there is one. Returns: `ResolvedContext`: Current context, or None if not in a resolved env. """ filepath = os.getenv("REZ_RXT_FILE") if not filepath or not os.path.exists(filepath): return None return cls.load(filepath)
[ "def", "get_current", "(", "cls", ")", ":", "filepath", "=", "os", ".", "getenv", "(", "\"REZ_RXT_FILE\"", ")", "if", "not", "filepath", "or", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "return", "None", "return", "cls", ".", "load", "(", "filepath", ")" ]
Get the context for the current env, if there is one. Returns: `ResolvedContext`: Current context, or None if not in a resolved env.
[ "Get", "the", "context", "for", "the", "current", "env", "if", "there", "is", "one", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L545-L555
232,645
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.load
def load(cls, path): """Load a resolved context from file.""" with open(path) as f: context = cls.read_from_buffer(f, path) context.set_load_path(path) return context
python
def load(cls, path): """Load a resolved context from file.""" with open(path) as f: context = cls.read_from_buffer(f, path) context.set_load_path(path) return context
[ "def", "load", "(", "cls", ",", "path", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "context", "=", "cls", ".", "read_from_buffer", "(", "f", ",", "path", ")", "context", ".", "set_load_path", "(", "path", ")", "return", "context" ]
Load a resolved context from file.
[ "Load", "a", "resolved", "context", "from", "file", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L558-L563
232,646
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.read_from_buffer
def read_from_buffer(cls, buf, identifier_str=None): """Load the context from a buffer.""" try: return cls._read_from_buffer(buf, identifier_str) except Exception as e: cls._load_error(e, identifier_str)
python
def read_from_buffer(cls, buf, identifier_str=None): """Load the context from a buffer.""" try: return cls._read_from_buffer(buf, identifier_str) except Exception as e: cls._load_error(e, identifier_str)
[ "def", "read_from_buffer", "(", "cls", ",", "buf", ",", "identifier_str", "=", "None", ")", ":", "try", ":", "return", "cls", ".", "_read_from_buffer", "(", "buf", ",", "identifier_str", ")", "except", "Exception", "as", "e", ":", "cls", ".", "_load_error", "(", "e", ",", "identifier_str", ")" ]
Load the context from a buffer.
[ "Load", "the", "context", "from", "a", "buffer", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L566-L571
232,647
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_resolve_diff
def get_resolve_diff(self, other): """Get the difference between the resolve in this context and another. The difference is described from the point of view of the current context - a newer package means that the package in `other` is newer than the package in `self`. Diffs can only be compared if their package search paths match, an error is raised otherwise. The diff is expressed in packages, not variants - the specific variant of a package is ignored. Returns: A dict containing: - 'newer_packages': A dict containing items: - package name (str); - List of `Package` objects. These are the packages up to and including the newer package in `self`, in ascending order. - 'older_packages': A dict containing: - package name (str); - List of `Package` objects. These are the packages down to and including the older package in `self`, in descending order. - 'added_packages': Set of `Package` objects present in `self` but not in `other`; - 'removed_packages': Set of `Package` objects present in `other`, but not in `self`. If any item ('added_packages' etc) is empty, it is not added to the resulting dict. Thus, an empty dict is returned if there is no difference between contexts. """ if self.package_paths != other.package_paths: from difflib import ndiff diff = ndiff(self.package_paths, other.package_paths) raise ResolvedContextError("Cannot diff resolves, package search " "paths differ:\n%s" % '\n'.join(diff)) d = {} self_pkgs_ = set(x.parent for x in self._resolved_packages) other_pkgs_ = set(x.parent for x in other._resolved_packages) self_pkgs = self_pkgs_ - other_pkgs_ other_pkgs = other_pkgs_ - self_pkgs_ if not (self_pkgs or other_pkgs): return d self_fams = dict((x.name, x) for x in self_pkgs) other_fams = dict((x.name, x) for x in other_pkgs) newer_packages = {} older_packages = {} added_packages = set() removed_packages = set() for pkg in self_pkgs: if pkg.name not in other_fams: removed_packages.add(pkg) else: other_pkg = other_fams[pkg.name] if other_pkg.version > pkg.version: r = VersionRange.as_span(lower_version=pkg.version, upper_version=other_pkg.version) it = iter_packages(pkg.name, range_=r) pkgs = sorted(it, key=lambda x: x.version) newer_packages[pkg.name] = pkgs elif other_pkg.version < pkg.version: r = VersionRange.as_span(lower_version=other_pkg.version, upper_version=pkg.version) it = iter_packages(pkg.name, range_=r) pkgs = sorted(it, key=lambda x: x.version, reverse=True) older_packages[pkg.name] = pkgs for pkg in other_pkgs: if pkg.name not in self_fams: added_packages.add(pkg) if newer_packages: d["newer_packages"] = newer_packages if older_packages: d["older_packages"] = older_packages if added_packages: d["added_packages"] = added_packages if removed_packages: d["removed_packages"] = removed_packages return d
python
def get_resolve_diff(self, other): """Get the difference between the resolve in this context and another. The difference is described from the point of view of the current context - a newer package means that the package in `other` is newer than the package in `self`. Diffs can only be compared if their package search paths match, an error is raised otherwise. The diff is expressed in packages, not variants - the specific variant of a package is ignored. Returns: A dict containing: - 'newer_packages': A dict containing items: - package name (str); - List of `Package` objects. These are the packages up to and including the newer package in `self`, in ascending order. - 'older_packages': A dict containing: - package name (str); - List of `Package` objects. These are the packages down to and including the older package in `self`, in descending order. - 'added_packages': Set of `Package` objects present in `self` but not in `other`; - 'removed_packages': Set of `Package` objects present in `other`, but not in `self`. If any item ('added_packages' etc) is empty, it is not added to the resulting dict. Thus, an empty dict is returned if there is no difference between contexts. """ if self.package_paths != other.package_paths: from difflib import ndiff diff = ndiff(self.package_paths, other.package_paths) raise ResolvedContextError("Cannot diff resolves, package search " "paths differ:\n%s" % '\n'.join(diff)) d = {} self_pkgs_ = set(x.parent for x in self._resolved_packages) other_pkgs_ = set(x.parent for x in other._resolved_packages) self_pkgs = self_pkgs_ - other_pkgs_ other_pkgs = other_pkgs_ - self_pkgs_ if not (self_pkgs or other_pkgs): return d self_fams = dict((x.name, x) for x in self_pkgs) other_fams = dict((x.name, x) for x in other_pkgs) newer_packages = {} older_packages = {} added_packages = set() removed_packages = set() for pkg in self_pkgs: if pkg.name not in other_fams: removed_packages.add(pkg) else: other_pkg = other_fams[pkg.name] if other_pkg.version > pkg.version: r = VersionRange.as_span(lower_version=pkg.version, upper_version=other_pkg.version) it = iter_packages(pkg.name, range_=r) pkgs = sorted(it, key=lambda x: x.version) newer_packages[pkg.name] = pkgs elif other_pkg.version < pkg.version: r = VersionRange.as_span(lower_version=other_pkg.version, upper_version=pkg.version) it = iter_packages(pkg.name, range_=r) pkgs = sorted(it, key=lambda x: x.version, reverse=True) older_packages[pkg.name] = pkgs for pkg in other_pkgs: if pkg.name not in self_fams: added_packages.add(pkg) if newer_packages: d["newer_packages"] = newer_packages if older_packages: d["older_packages"] = older_packages if added_packages: d["added_packages"] = added_packages if removed_packages: d["removed_packages"] = removed_packages return d
[ "def", "get_resolve_diff", "(", "self", ",", "other", ")", ":", "if", "self", ".", "package_paths", "!=", "other", ".", "package_paths", ":", "from", "difflib", "import", "ndiff", "diff", "=", "ndiff", "(", "self", ".", "package_paths", ",", "other", ".", "package_paths", ")", "raise", "ResolvedContextError", "(", "\"Cannot diff resolves, package search \"", "\"paths differ:\\n%s\"", "%", "'\\n'", ".", "join", "(", "diff", ")", ")", "d", "=", "{", "}", "self_pkgs_", "=", "set", "(", "x", ".", "parent", "for", "x", "in", "self", ".", "_resolved_packages", ")", "other_pkgs_", "=", "set", "(", "x", ".", "parent", "for", "x", "in", "other", ".", "_resolved_packages", ")", "self_pkgs", "=", "self_pkgs_", "-", "other_pkgs_", "other_pkgs", "=", "other_pkgs_", "-", "self_pkgs_", "if", "not", "(", "self_pkgs", "or", "other_pkgs", ")", ":", "return", "d", "self_fams", "=", "dict", "(", "(", "x", ".", "name", ",", "x", ")", "for", "x", "in", "self_pkgs", ")", "other_fams", "=", "dict", "(", "(", "x", ".", "name", ",", "x", ")", "for", "x", "in", "other_pkgs", ")", "newer_packages", "=", "{", "}", "older_packages", "=", "{", "}", "added_packages", "=", "set", "(", ")", "removed_packages", "=", "set", "(", ")", "for", "pkg", "in", "self_pkgs", ":", "if", "pkg", ".", "name", "not", "in", "other_fams", ":", "removed_packages", ".", "add", "(", "pkg", ")", "else", ":", "other_pkg", "=", "other_fams", "[", "pkg", ".", "name", "]", "if", "other_pkg", ".", "version", ">", "pkg", ".", "version", ":", "r", "=", "VersionRange", ".", "as_span", "(", "lower_version", "=", "pkg", ".", "version", ",", "upper_version", "=", "other_pkg", ".", "version", ")", "it", "=", "iter_packages", "(", "pkg", ".", "name", ",", "range_", "=", "r", ")", "pkgs", "=", "sorted", "(", "it", ",", "key", "=", "lambda", "x", ":", "x", ".", "version", ")", "newer_packages", "[", "pkg", ".", "name", "]", "=", "pkgs", "elif", "other_pkg", ".", "version", "<", "pkg", ".", "version", ":", "r", "=", "VersionRange", ".", "as_span", "(", "lower_version", "=", "other_pkg", ".", "version", ",", "upper_version", "=", "pkg", ".", "version", ")", "it", "=", "iter_packages", "(", "pkg", ".", "name", ",", "range_", "=", "r", ")", "pkgs", "=", "sorted", "(", "it", ",", "key", "=", "lambda", "x", ":", "x", ".", "version", ",", "reverse", "=", "True", ")", "older_packages", "[", "pkg", ".", "name", "]", "=", "pkgs", "for", "pkg", "in", "other_pkgs", ":", "if", "pkg", ".", "name", "not", "in", "self_fams", ":", "added_packages", ".", "add", "(", "pkg", ")", "if", "newer_packages", ":", "d", "[", "\"newer_packages\"", "]", "=", "newer_packages", "if", "older_packages", ":", "d", "[", "\"older_packages\"", "]", "=", "older_packages", "if", "added_packages", ":", "d", "[", "\"added_packages\"", "]", "=", "added_packages", "if", "removed_packages", ":", "d", "[", "\"removed_packages\"", "]", "=", "removed_packages", "return", "d" ]
Get the difference between the resolve in this context and another. The difference is described from the point of view of the current context - a newer package means that the package in `other` is newer than the package in `self`. Diffs can only be compared if their package search paths match, an error is raised otherwise. The diff is expressed in packages, not variants - the specific variant of a package is ignored. Returns: A dict containing: - 'newer_packages': A dict containing items: - package name (str); - List of `Package` objects. These are the packages up to and including the newer package in `self`, in ascending order. - 'older_packages': A dict containing: - package name (str); - List of `Package` objects. These are the packages down to and including the older package in `self`, in descending order. - 'added_packages': Set of `Package` objects present in `self` but not in `other`; - 'removed_packages': Set of `Package` objects present in `other`, but not in `self`. If any item ('added_packages' etc) is empty, it is not added to the resulting dict. Thus, an empty dict is returned if there is no difference between contexts.
[ "Get", "the", "difference", "between", "the", "resolve", "in", "this", "context", "and", "another", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L573-L657
232,648
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.print_resolve_diff
def print_resolve_diff(self, other, heading=None): """Print the difference between the resolve of two contexts. Args: other (`ResolvedContext`): Context to compare to. heading: One of: - None: Do not display a heading; - True: Display the filename of each context as a heading, if both contexts have a filepath; - 2-tuple: Use the given two strings as headings - the first is the heading for `self`, the second for `other`. """ d = self.get_resolve_diff(other) if not d: return rows = [] if heading is True and self.load_path and other.load_path: a = os.path.basename(self.load_path) b = os.path.basename(other.load_path) heading = (a, b) if isinstance(heading, tuple): rows.append(list(heading) + [""]) rows.append(('-' * len(heading[0]), '-' * len(heading[1]), "")) newer_packages = d.get("newer_packages", {}) older_packages = d.get("older_packages", {}) added_packages = d.get("added_packages", set()) removed_packages = d.get("removed_packages", set()) if newer_packages: for name, pkgs in newer_packages.iteritems(): this_pkg = pkgs[0] other_pkg = pkgs[-1] diff_str = "(+%d versions)" % (len(pkgs) - 1) rows.append((this_pkg.qualified_name, other_pkg.qualified_name, diff_str)) if older_packages: for name, pkgs in older_packages.iteritems(): this_pkg = pkgs[0] other_pkg = pkgs[-1] diff_str = "(-%d versions)" % (len(pkgs) - 1) rows.append((this_pkg.qualified_name, other_pkg.qualified_name, diff_str)) if added_packages: for pkg in sorted(added_packages, key=lambda x: x.name): rows.append(("-", pkg.qualified_name, "")) if removed_packages: for pkg in sorted(removed_packages, key=lambda x: x.name): rows.append((pkg.qualified_name, "-", "")) print '\n'.join(columnise(rows))
python
def print_resolve_diff(self, other, heading=None): """Print the difference between the resolve of two contexts. Args: other (`ResolvedContext`): Context to compare to. heading: One of: - None: Do not display a heading; - True: Display the filename of each context as a heading, if both contexts have a filepath; - 2-tuple: Use the given two strings as headings - the first is the heading for `self`, the second for `other`. """ d = self.get_resolve_diff(other) if not d: return rows = [] if heading is True and self.load_path and other.load_path: a = os.path.basename(self.load_path) b = os.path.basename(other.load_path) heading = (a, b) if isinstance(heading, tuple): rows.append(list(heading) + [""]) rows.append(('-' * len(heading[0]), '-' * len(heading[1]), "")) newer_packages = d.get("newer_packages", {}) older_packages = d.get("older_packages", {}) added_packages = d.get("added_packages", set()) removed_packages = d.get("removed_packages", set()) if newer_packages: for name, pkgs in newer_packages.iteritems(): this_pkg = pkgs[0] other_pkg = pkgs[-1] diff_str = "(+%d versions)" % (len(pkgs) - 1) rows.append((this_pkg.qualified_name, other_pkg.qualified_name, diff_str)) if older_packages: for name, pkgs in older_packages.iteritems(): this_pkg = pkgs[0] other_pkg = pkgs[-1] diff_str = "(-%d versions)" % (len(pkgs) - 1) rows.append((this_pkg.qualified_name, other_pkg.qualified_name, diff_str)) if added_packages: for pkg in sorted(added_packages, key=lambda x: x.name): rows.append(("-", pkg.qualified_name, "")) if removed_packages: for pkg in sorted(removed_packages, key=lambda x: x.name): rows.append((pkg.qualified_name, "-", "")) print '\n'.join(columnise(rows))
[ "def", "print_resolve_diff", "(", "self", ",", "other", ",", "heading", "=", "None", ")", ":", "d", "=", "self", ".", "get_resolve_diff", "(", "other", ")", "if", "not", "d", ":", "return", "rows", "=", "[", "]", "if", "heading", "is", "True", "and", "self", ".", "load_path", "and", "other", ".", "load_path", ":", "a", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "load_path", ")", "b", "=", "os", ".", "path", ".", "basename", "(", "other", ".", "load_path", ")", "heading", "=", "(", "a", ",", "b", ")", "if", "isinstance", "(", "heading", ",", "tuple", ")", ":", "rows", ".", "append", "(", "list", "(", "heading", ")", "+", "[", "\"\"", "]", ")", "rows", ".", "append", "(", "(", "'-'", "*", "len", "(", "heading", "[", "0", "]", ")", ",", "'-'", "*", "len", "(", "heading", "[", "1", "]", ")", ",", "\"\"", ")", ")", "newer_packages", "=", "d", ".", "get", "(", "\"newer_packages\"", ",", "{", "}", ")", "older_packages", "=", "d", ".", "get", "(", "\"older_packages\"", ",", "{", "}", ")", "added_packages", "=", "d", ".", "get", "(", "\"added_packages\"", ",", "set", "(", ")", ")", "removed_packages", "=", "d", ".", "get", "(", "\"removed_packages\"", ",", "set", "(", ")", ")", "if", "newer_packages", ":", "for", "name", ",", "pkgs", "in", "newer_packages", ".", "iteritems", "(", ")", ":", "this_pkg", "=", "pkgs", "[", "0", "]", "other_pkg", "=", "pkgs", "[", "-", "1", "]", "diff_str", "=", "\"(+%d versions)\"", "%", "(", "len", "(", "pkgs", ")", "-", "1", ")", "rows", ".", "append", "(", "(", "this_pkg", ".", "qualified_name", ",", "other_pkg", ".", "qualified_name", ",", "diff_str", ")", ")", "if", "older_packages", ":", "for", "name", ",", "pkgs", "in", "older_packages", ".", "iteritems", "(", ")", ":", "this_pkg", "=", "pkgs", "[", "0", "]", "other_pkg", "=", "pkgs", "[", "-", "1", "]", "diff_str", "=", "\"(-%d versions)\"", "%", "(", "len", "(", "pkgs", ")", "-", "1", ")", "rows", ".", "append", "(", "(", "this_pkg", ".", "qualified_name", ",", "other_pkg", ".", "qualified_name", ",", "diff_str", ")", ")", "if", "added_packages", ":", "for", "pkg", "in", "sorted", "(", "added_packages", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")", ":", "rows", ".", "append", "(", "(", "\"-\"", ",", "pkg", ".", "qualified_name", ",", "\"\"", ")", ")", "if", "removed_packages", ":", "for", "pkg", "in", "sorted", "(", "removed_packages", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")", ":", "rows", ".", "append", "(", "(", "pkg", ".", "qualified_name", ",", "\"-\"", ",", "\"\"", ")", ")", "print", "'\\n'", ".", "join", "(", "columnise", "(", "rows", ")", ")" ]
Print the difference between the resolve of two contexts. Args: other (`ResolvedContext`): Context to compare to. heading: One of: - None: Do not display a heading; - True: Display the filename of each context as a heading, if both contexts have a filepath; - 2-tuple: Use the given two strings as headings - the first is the heading for `self`, the second for `other`.
[ "Print", "the", "difference", "between", "the", "resolve", "of", "two", "contexts", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L809-L865
232,649
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_dependency_graph
def get_dependency_graph(self): """Generate the dependency graph. The dependency graph is a simpler subset of the resolve graph. It contains package name nodes connected directly to their dependencies. Weak references and conflict requests are not included in the graph. The dependency graph does not show conflicts. Returns: `pygraph.digraph` object. """ from rez.vendor.pygraph.classes.digraph import digraph nodes = {} edges = set() for variant in self._resolved_packages: nodes[variant.name] = variant.qualified_package_name for request in variant.get_requires(): if not request.conflict: edges.add((variant.name, request.name)) g = digraph() node_color = "#AAFFAA" node_fontsize = 10 attrs = [("fontsize", node_fontsize), ("fillcolor", node_color), ("style", "filled")] for name, qname in nodes.iteritems(): g.add_node(name, attrs=attrs + [("label", qname)]) for edge in edges: g.add_edge(edge) return g
python
def get_dependency_graph(self): """Generate the dependency graph. The dependency graph is a simpler subset of the resolve graph. It contains package name nodes connected directly to their dependencies. Weak references and conflict requests are not included in the graph. The dependency graph does not show conflicts. Returns: `pygraph.digraph` object. """ from rez.vendor.pygraph.classes.digraph import digraph nodes = {} edges = set() for variant in self._resolved_packages: nodes[variant.name] = variant.qualified_package_name for request in variant.get_requires(): if not request.conflict: edges.add((variant.name, request.name)) g = digraph() node_color = "#AAFFAA" node_fontsize = 10 attrs = [("fontsize", node_fontsize), ("fillcolor", node_color), ("style", "filled")] for name, qname in nodes.iteritems(): g.add_node(name, attrs=attrs + [("label", qname)]) for edge in edges: g.add_edge(edge) return g
[ "def", "get_dependency_graph", "(", "self", ")", ":", "from", "rez", ".", "vendor", ".", "pygraph", ".", "classes", ".", "digraph", "import", "digraph", "nodes", "=", "{", "}", "edges", "=", "set", "(", ")", "for", "variant", "in", "self", ".", "_resolved_packages", ":", "nodes", "[", "variant", ".", "name", "]", "=", "variant", ".", "qualified_package_name", "for", "request", "in", "variant", ".", "get_requires", "(", ")", ":", "if", "not", "request", ".", "conflict", ":", "edges", ".", "add", "(", "(", "variant", ".", "name", ",", "request", ".", "name", ")", ")", "g", "=", "digraph", "(", ")", "node_color", "=", "\"#AAFFAA\"", "node_fontsize", "=", "10", "attrs", "=", "[", "(", "\"fontsize\"", ",", "node_fontsize", ")", ",", "(", "\"fillcolor\"", ",", "node_color", ")", ",", "(", "\"style\"", ",", "\"filled\"", ")", "]", "for", "name", ",", "qname", "in", "nodes", ".", "iteritems", "(", ")", ":", "g", ".", "add_node", "(", "name", ",", "attrs", "=", "attrs", "+", "[", "(", "\"label\"", ",", "qname", ")", "]", ")", "for", "edge", "in", "edges", ":", "g", ".", "add_edge", "(", "edge", ")", "return", "g" ]
Generate the dependency graph. The dependency graph is a simpler subset of the resolve graph. It contains package name nodes connected directly to their dependencies. Weak references and conflict requests are not included in the graph. The dependency graph does not show conflicts. Returns: `pygraph.digraph` object.
[ "Generate", "the", "dependency", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L878-L910
232,650
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.validate
def validate(self): """Validate the context.""" try: for pkg in self.resolved_packages: pkg.validate_data() except RezError as e: raise ResolvedContextError("%s: %s" % (e.__class__.__name__, str(e)))
python
def validate(self): """Validate the context.""" try: for pkg in self.resolved_packages: pkg.validate_data() except RezError as e: raise ResolvedContextError("%s: %s" % (e.__class__.__name__, str(e)))
[ "def", "validate", "(", "self", ")", ":", "try", ":", "for", "pkg", "in", "self", ".", "resolved_packages", ":", "pkg", ".", "validate_data", "(", ")", "except", "RezError", "as", "e", ":", "raise", "ResolvedContextError", "(", "\"%s: %s\"", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "str", "(", "e", ")", ")", ")" ]
Validate the context.
[ "Validate", "the", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L913-L919
232,651
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_environ
def get_environ(self, parent_environ=None): """Get the environ dict resulting from interpreting this context. @param parent_environ Environment to interpret the context within, defaults to os.environ if None. @returns The environment dict generated by this context, when interpreted in a python rex interpreter. """ interp = Python(target_environ={}, passive=True) executor = self._create_executor(interp, parent_environ) self._execute(executor) return executor.get_output()
python
def get_environ(self, parent_environ=None): """Get the environ dict resulting from interpreting this context. @param parent_environ Environment to interpret the context within, defaults to os.environ if None. @returns The environment dict generated by this context, when interpreted in a python rex interpreter. """ interp = Python(target_environ={}, passive=True) executor = self._create_executor(interp, parent_environ) self._execute(executor) return executor.get_output()
[ "def", "get_environ", "(", "self", ",", "parent_environ", "=", "None", ")", ":", "interp", "=", "Python", "(", "target_environ", "=", "{", "}", ",", "passive", "=", "True", ")", "executor", "=", "self", ".", "_create_executor", "(", "interp", ",", "parent_environ", ")", "self", ".", "_execute", "(", "executor", ")", "return", "executor", ".", "get_output", "(", ")" ]
Get the environ dict resulting from interpreting this context. @param parent_environ Environment to interpret the context within, defaults to os.environ if None. @returns The environment dict generated by this context, when interpreted in a python rex interpreter.
[ "Get", "the", "environ", "dict", "resulting", "from", "interpreting", "this", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L922-L933
232,652
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_key
def get_key(self, key, request_only=False): """Get a data key value for each resolved package. Args: key (str): String key of property, eg 'tools'. request_only (bool): If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {pkg-name: (variant, value)}. """ values = {} requested_names = [x.name for x in self._package_requests if not x.conflict] for pkg in self.resolved_packages: if (not request_only) or (pkg.name in requested_names): value = getattr(pkg, key) if value is not None: values[pkg.name] = (pkg, value) return values
python
def get_key(self, key, request_only=False): """Get a data key value for each resolved package. Args: key (str): String key of property, eg 'tools'. request_only (bool): If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {pkg-name: (variant, value)}. """ values = {} requested_names = [x.name for x in self._package_requests if not x.conflict] for pkg in self.resolved_packages: if (not request_only) or (pkg.name in requested_names): value = getattr(pkg, key) if value is not None: values[pkg.name] = (pkg, value) return values
[ "def", "get_key", "(", "self", ",", "key", ",", "request_only", "=", "False", ")", ":", "values", "=", "{", "}", "requested_names", "=", "[", "x", ".", "name", "for", "x", "in", "self", ".", "_package_requests", "if", "not", "x", ".", "conflict", "]", "for", "pkg", "in", "self", ".", "resolved_packages", ":", "if", "(", "not", "request_only", ")", "or", "(", "pkg", ".", "name", "in", "requested_names", ")", ":", "value", "=", "getattr", "(", "pkg", ",", "key", ")", "if", "value", "is", "not", "None", ":", "values", "[", "pkg", ".", "name", "]", "=", "(", "pkg", ",", "value", ")", "return", "values" ]
Get a data key value for each resolved package. Args: key (str): String key of property, eg 'tools'. request_only (bool): If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {pkg-name: (variant, value)}.
[ "Get", "a", "data", "key", "value", "for", "each", "resolved", "package", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L936-L957
232,653
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_conflicting_tools
def get_conflicting_tools(self, request_only=False): """Returns tools of the same name provided by more than one package. Args: request_only: If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {tool-name: set([Variant])}. """ from collections import defaultdict tool_sets = defaultdict(set) tools_dict = self.get_tools(request_only=request_only) for variant, tools in tools_dict.itervalues(): for tool in tools: tool_sets[tool].add(variant) conflicts = dict((k, v) for k, v in tool_sets.iteritems() if len(v) > 1) return conflicts
python
def get_conflicting_tools(self, request_only=False): """Returns tools of the same name provided by more than one package. Args: request_only: If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {tool-name: set([Variant])}. """ from collections import defaultdict tool_sets = defaultdict(set) tools_dict = self.get_tools(request_only=request_only) for variant, tools in tools_dict.itervalues(): for tool in tools: tool_sets[tool].add(variant) conflicts = dict((k, v) for k, v in tool_sets.iteritems() if len(v) > 1) return conflicts
[ "def", "get_conflicting_tools", "(", "self", ",", "request_only", "=", "False", ")", ":", "from", "collections", "import", "defaultdict", "tool_sets", "=", "defaultdict", "(", "set", ")", "tools_dict", "=", "self", ".", "get_tools", "(", "request_only", "=", "request_only", ")", "for", "variant", ",", "tools", "in", "tools_dict", ".", "itervalues", "(", ")", ":", "for", "tool", "in", "tools", ":", "tool_sets", "[", "tool", "]", ".", "add", "(", "variant", ")", "conflicts", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "tool_sets", ".", "iteritems", "(", ")", "if", "len", "(", "v", ")", ">", "1", ")", "return", "conflicts" ]
Returns tools of the same name provided by more than one package. Args: request_only: If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {tool-name: set([Variant])}.
[ "Returns", "tools", "of", "the", "same", "name", "provided", "by", "more", "than", "one", "package", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L994-L1013
232,654
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_shell_code
def get_shell_code(self, shell=None, parent_environ=None, style=OutputStyle.file): """Get the shell code resulting from intepreting this context. Args: shell (str): Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ (dict): Environment to interpret the context within, defaults to os.environ if None. style (): Style to format shell code in. """ executor = self._create_executor(interpreter=create_shell(shell), parent_environ=parent_environ) if self.load_path and os.path.isfile(self.load_path): executor.env.REZ_RXT_FILE = self.load_path self._execute(executor) return executor.get_output(style)
python
def get_shell_code(self, shell=None, parent_environ=None, style=OutputStyle.file): """Get the shell code resulting from intepreting this context. Args: shell (str): Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ (dict): Environment to interpret the context within, defaults to os.environ if None. style (): Style to format shell code in. """ executor = self._create_executor(interpreter=create_shell(shell), parent_environ=parent_environ) if self.load_path and os.path.isfile(self.load_path): executor.env.REZ_RXT_FILE = self.load_path self._execute(executor) return executor.get_output(style)
[ "def", "get_shell_code", "(", "self", ",", "shell", "=", "None", ",", "parent_environ", "=", "None", ",", "style", "=", "OutputStyle", ".", "file", ")", ":", "executor", "=", "self", ".", "_create_executor", "(", "interpreter", "=", "create_shell", "(", "shell", ")", ",", "parent_environ", "=", "parent_environ", ")", "if", "self", ".", "load_path", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "load_path", ")", ":", "executor", ".", "env", ".", "REZ_RXT_FILE", "=", "self", ".", "load_path", "self", ".", "_execute", "(", "executor", ")", "return", "executor", ".", "get_output", "(", "style", ")" ]
Get the shell code resulting from intepreting this context. Args: shell (str): Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ (dict): Environment to interpret the context within, defaults to os.environ if None. style (): Style to format shell code in.
[ "Get", "the", "shell", "code", "resulting", "from", "intepreting", "this", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1016-L1033
232,655
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.get_actions
def get_actions(self, parent_environ=None): """Get the list of rex.Action objects resulting from interpreting this context. This is provided mainly for testing purposes. Args: parent_environ Environment to interpret the context within, defaults to os.environ if None. Returns: A list of rex.Action subclass instances. """ interp = Python(target_environ={}, passive=True) executor = self._create_executor(interp, parent_environ) self._execute(executor) return executor.actions
python
def get_actions(self, parent_environ=None): """Get the list of rex.Action objects resulting from interpreting this context. This is provided mainly for testing purposes. Args: parent_environ Environment to interpret the context within, defaults to os.environ if None. Returns: A list of rex.Action subclass instances. """ interp = Python(target_environ={}, passive=True) executor = self._create_executor(interp, parent_environ) self._execute(executor) return executor.actions
[ "def", "get_actions", "(", "self", ",", "parent_environ", "=", "None", ")", ":", "interp", "=", "Python", "(", "target_environ", "=", "{", "}", ",", "passive", "=", "True", ")", "executor", "=", "self", ".", "_create_executor", "(", "interp", ",", "parent_environ", ")", "self", ".", "_execute", "(", "executor", ")", "return", "executor", ".", "actions" ]
Get the list of rex.Action objects resulting from interpreting this context. This is provided mainly for testing purposes. Args: parent_environ Environment to interpret the context within, defaults to os.environ if None. Returns: A list of rex.Action subclass instances.
[ "Get", "the", "list", "of", "rex", ".", "Action", "objects", "resulting", "from", "interpreting", "this", "context", ".", "This", "is", "provided", "mainly", "for", "testing", "purposes", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1036-L1050
232,656
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.apply
def apply(self, parent_environ=None): """Apply the context to the current python session. Note that this updates os.environ and possibly sys.path, if `parent_environ` is not provided. Args: parent_environ: Environment to interpret the context within, defaults to os.environ if None. """ interpreter = Python(target_environ=os.environ) executor = self._create_executor(interpreter, parent_environ) self._execute(executor) interpreter.apply_environ()
python
def apply(self, parent_environ=None): """Apply the context to the current python session. Note that this updates os.environ and possibly sys.path, if `parent_environ` is not provided. Args: parent_environ: Environment to interpret the context within, defaults to os.environ if None. """ interpreter = Python(target_environ=os.environ) executor = self._create_executor(interpreter, parent_environ) self._execute(executor) interpreter.apply_environ()
[ "def", "apply", "(", "self", ",", "parent_environ", "=", "None", ")", ":", "interpreter", "=", "Python", "(", "target_environ", "=", "os", ".", "environ", ")", "executor", "=", "self", ".", "_create_executor", "(", "interpreter", ",", "parent_environ", ")", "self", ".", "_execute", "(", "executor", ")", "interpreter", ".", "apply_environ", "(", ")" ]
Apply the context to the current python session. Note that this updates os.environ and possibly sys.path, if `parent_environ` is not provided. Args: parent_environ: Environment to interpret the context within, defaults to os.environ if None.
[ "Apply", "the", "context", "to", "the", "current", "python", "session", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1053-L1066
232,657
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.which
def which(self, cmd, parent_environ=None, fallback=False): """Find a program in the resolved environment. Args: cmd: String name of the program to find. parent_environ: Environment to interpret the context within, defaults to os.environ if None. fallback: If True, and the program is not found in the context, the current environment will then be searched. Returns: Path to the program, or None if the program was not found. """ env = self.get_environ(parent_environ=parent_environ) path = which(cmd, env=env) if fallback and path is None: path = which(cmd) return path
python
def which(self, cmd, parent_environ=None, fallback=False): """Find a program in the resolved environment. Args: cmd: String name of the program to find. parent_environ: Environment to interpret the context within, defaults to os.environ if None. fallback: If True, and the program is not found in the context, the current environment will then be searched. Returns: Path to the program, or None if the program was not found. """ env = self.get_environ(parent_environ=parent_environ) path = which(cmd, env=env) if fallback and path is None: path = which(cmd) return path
[ "def", "which", "(", "self", ",", "cmd", ",", "parent_environ", "=", "None", ",", "fallback", "=", "False", ")", ":", "env", "=", "self", ".", "get_environ", "(", "parent_environ", "=", "parent_environ", ")", "path", "=", "which", "(", "cmd", ",", "env", "=", "env", ")", "if", "fallback", "and", "path", "is", "None", ":", "path", "=", "which", "(", "cmd", ")", "return", "path" ]
Find a program in the resolved environment. Args: cmd: String name of the program to find. parent_environ: Environment to interpret the context within, defaults to os.environ if None. fallback: If True, and the program is not found in the context, the current environment will then be searched. Returns: Path to the program, or None if the program was not found.
[ "Find", "a", "program", "in", "the", "resolved", "environment", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1069-L1086
232,658
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.execute_command
def execute_command(self, args, parent_environ=None, **subprocess_kwargs): """Run a command within a resolved context. This applies the context to a python environ dict, then runs a subprocess in that namespace. This is not a fully configured subshell - shell-specific commands such as aliases will not be applied. To execute a command within a subshell instead, use execute_shell(). Warning: This runs a command in a configured environ dict only, not in a true shell. To do that, call `execute_shell` using the `command` keyword argument. Args: args: Command arguments, can be a string. parent_environ: Environment to interpret the context within, defaults to os.environ if None. subprocess_kwargs: Args to pass to subprocess.Popen. Returns: A subprocess.Popen object. Note: This does not alter the current python session. """ if parent_environ in (None, os.environ): target_environ = {} else: target_environ = parent_environ.copy() interpreter = Python(target_environ=target_environ) executor = self._create_executor(interpreter, parent_environ) self._execute(executor) return interpreter.subprocess(args, **subprocess_kwargs)
python
def execute_command(self, args, parent_environ=None, **subprocess_kwargs): """Run a command within a resolved context. This applies the context to a python environ dict, then runs a subprocess in that namespace. This is not a fully configured subshell - shell-specific commands such as aliases will not be applied. To execute a command within a subshell instead, use execute_shell(). Warning: This runs a command in a configured environ dict only, not in a true shell. To do that, call `execute_shell` using the `command` keyword argument. Args: args: Command arguments, can be a string. parent_environ: Environment to interpret the context within, defaults to os.environ if None. subprocess_kwargs: Args to pass to subprocess.Popen. Returns: A subprocess.Popen object. Note: This does not alter the current python session. """ if parent_environ in (None, os.environ): target_environ = {} else: target_environ = parent_environ.copy() interpreter = Python(target_environ=target_environ) executor = self._create_executor(interpreter, parent_environ) self._execute(executor) return interpreter.subprocess(args, **subprocess_kwargs)
[ "def", "execute_command", "(", "self", ",", "args", ",", "parent_environ", "=", "None", ",", "*", "*", "subprocess_kwargs", ")", ":", "if", "parent_environ", "in", "(", "None", ",", "os", ".", "environ", ")", ":", "target_environ", "=", "{", "}", "else", ":", "target_environ", "=", "parent_environ", ".", "copy", "(", ")", "interpreter", "=", "Python", "(", "target_environ", "=", "target_environ", ")", "executor", "=", "self", ".", "_create_executor", "(", "interpreter", ",", "parent_environ", ")", "self", ".", "_execute", "(", "executor", ")", "return", "interpreter", ".", "subprocess", "(", "args", ",", "*", "*", "subprocess_kwargs", ")" ]
Run a command within a resolved context. This applies the context to a python environ dict, then runs a subprocess in that namespace. This is not a fully configured subshell - shell-specific commands such as aliases will not be applied. To execute a command within a subshell instead, use execute_shell(). Warning: This runs a command in a configured environ dict only, not in a true shell. To do that, call `execute_shell` using the `command` keyword argument. Args: args: Command arguments, can be a string. parent_environ: Environment to interpret the context within, defaults to os.environ if None. subprocess_kwargs: Args to pass to subprocess.Popen. Returns: A subprocess.Popen object. Note: This does not alter the current python session.
[ "Run", "a", "command", "within", "a", "resolved", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1089-L1123
232,659
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.execute_rex_code
def execute_rex_code(self, code, filename=None, shell=None, parent_environ=None, **Popen_args): """Run some rex code in the context. Note: This is just a convenience form of `execute_shell`. Args: code (str): Rex code to execute. filename (str): Filename to report if there are syntax errors. shell: Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ: Environment to run the shell process in, if None then the current environment is used. Popen_args: args to pass to the shell process object constructor. Returns: `subprocess.Popen` object for the shell process. """ def _actions_callback(executor): executor.execute_code(code, filename=filename) return self.execute_shell(shell=shell, parent_environ=parent_environ, command='', # don't run any command block=False, actions_callback=_actions_callback, **Popen_args)
python
def execute_rex_code(self, code, filename=None, shell=None, parent_environ=None, **Popen_args): """Run some rex code in the context. Note: This is just a convenience form of `execute_shell`. Args: code (str): Rex code to execute. filename (str): Filename to report if there are syntax errors. shell: Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ: Environment to run the shell process in, if None then the current environment is used. Popen_args: args to pass to the shell process object constructor. Returns: `subprocess.Popen` object for the shell process. """ def _actions_callback(executor): executor.execute_code(code, filename=filename) return self.execute_shell(shell=shell, parent_environ=parent_environ, command='', # don't run any command block=False, actions_callback=_actions_callback, **Popen_args)
[ "def", "execute_rex_code", "(", "self", ",", "code", ",", "filename", "=", "None", ",", "shell", "=", "None", ",", "parent_environ", "=", "None", ",", "*", "*", "Popen_args", ")", ":", "def", "_actions_callback", "(", "executor", ")", ":", "executor", ".", "execute_code", "(", "code", ",", "filename", "=", "filename", ")", "return", "self", ".", "execute_shell", "(", "shell", "=", "shell", ",", "parent_environ", "=", "parent_environ", ",", "command", "=", "''", ",", "# don't run any command", "block", "=", "False", ",", "actions_callback", "=", "_actions_callback", ",", "*", "*", "Popen_args", ")" ]
Run some rex code in the context. Note: This is just a convenience form of `execute_shell`. Args: code (str): Rex code to execute. filename (str): Filename to report if there are syntax errors. shell: Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ: Environment to run the shell process in, if None then the current environment is used. Popen_args: args to pass to the shell process object constructor. Returns: `subprocess.Popen` object for the shell process.
[ "Run", "some", "rex", "code", "in", "the", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1126-L1153
232,660
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.execute_shell
def execute_shell(self, shell=None, parent_environ=None, rcfile=None, norc=False, stdin=False, command=None, quiet=False, block=None, actions_callback=None, post_actions_callback=None, context_filepath=None, start_new_session=False, detached=False, pre_command=None, **Popen_args): """Spawn a possibly-interactive shell. Args: shell: Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ: Environment to run the shell process in, if None then the current environment is used. rcfile: Specify a file to source instead of shell startup files. norc: If True, skip shell startup files, if possible. stdin: If True, read commands from stdin, in a non-interactive shell. command: If not None, execute this command in a non-interactive shell. If an empty string or list, don't run a command, but don't open an interactive shell either. Can be a list of args. quiet: If True, skip the welcome message in interactive shells. block: If True, block until the shell is terminated. If False, return immediately. If None, will default to blocking if the shell is interactive. actions_callback: Callback with signature (RexExecutor). This lets the user append custom actions to the context, such as setting extra environment variables. Callback is run prior to context Rex execution. post_actions_callback: Callback with signature (RexExecutor). This lets the user append custom actions to the context, such as setting extra environment variables. Callback is run after context Rex execution. context_filepath: If provided, the context file will be written here, rather than to the default location (which is in a tempdir). If you use this arg, you are responsible for cleaning up the file. start_new_session: If True, change the process group of the target process. Note that this may override the Popen_args keyword 'preexec_fn'. detached: If True, open a separate terminal. Note that this may override the `pre_command` argument. pre_command: Command to inject before the shell command itself. This is for internal use. Popen_args: args to pass to the shell process object constructor. Returns: If blocking: A 3-tuple of (returncode, stdout, stderr); If non-blocking - A subprocess.Popen object for the shell process. """ sh = create_shell(shell) if hasattr(command, "__iter__"): command = sh.join(command) # start a new session if specified if start_new_session: Popen_args.update(config.new_session_popen_args) # open a separate terminal if specified if detached: term_cmd = config.terminal_emulator_command if term_cmd: pre_command = term_cmd.strip().split() # block if the shell is likely to be interactive if block is None: block = not (command or stdin) # context and rxt files. If running detached, don't cleanup files, because # rez-env returns too early and deletes the tmp files before the detached # process can use them tmpdir = self.tmpdir_manager.mkdtemp(cleanup=not detached) if self.load_path and os.path.isfile(self.load_path): rxt_file = self.load_path else: rxt_file = os.path.join(tmpdir, "context.rxt") self.save(rxt_file) context_file = context_filepath or \ os.path.join(tmpdir, "context.%s" % sh.file_extension()) # interpret this context and write out the native context file executor = self._create_executor(sh, parent_environ) executor.env.REZ_RXT_FILE = rxt_file executor.env.REZ_CONTEXT_FILE = context_file if actions_callback: actions_callback(executor) self._execute(executor) if post_actions_callback: post_actions_callback(executor) context_code = executor.get_output() with open(context_file, 'w') as f: f.write(context_code) quiet = quiet or \ (RezToolsVisibility[config.rez_tools_visibility] == RezToolsVisibility.never) # spawn the shell subprocess p = sh.spawn_shell(context_file, tmpdir, rcfile=rcfile, norc=norc, stdin=stdin, command=command, env=parent_environ, quiet=quiet, pre_command=pre_command, **Popen_args) if block: stdout, stderr = p.communicate() return p.returncode, stdout, stderr else: return p
python
def execute_shell(self, shell=None, parent_environ=None, rcfile=None, norc=False, stdin=False, command=None, quiet=False, block=None, actions_callback=None, post_actions_callback=None, context_filepath=None, start_new_session=False, detached=False, pre_command=None, **Popen_args): """Spawn a possibly-interactive shell. Args: shell: Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ: Environment to run the shell process in, if None then the current environment is used. rcfile: Specify a file to source instead of shell startup files. norc: If True, skip shell startup files, if possible. stdin: If True, read commands from stdin, in a non-interactive shell. command: If not None, execute this command in a non-interactive shell. If an empty string or list, don't run a command, but don't open an interactive shell either. Can be a list of args. quiet: If True, skip the welcome message in interactive shells. block: If True, block until the shell is terminated. If False, return immediately. If None, will default to blocking if the shell is interactive. actions_callback: Callback with signature (RexExecutor). This lets the user append custom actions to the context, such as setting extra environment variables. Callback is run prior to context Rex execution. post_actions_callback: Callback with signature (RexExecutor). This lets the user append custom actions to the context, such as setting extra environment variables. Callback is run after context Rex execution. context_filepath: If provided, the context file will be written here, rather than to the default location (which is in a tempdir). If you use this arg, you are responsible for cleaning up the file. start_new_session: If True, change the process group of the target process. Note that this may override the Popen_args keyword 'preexec_fn'. detached: If True, open a separate terminal. Note that this may override the `pre_command` argument. pre_command: Command to inject before the shell command itself. This is for internal use. Popen_args: args to pass to the shell process object constructor. Returns: If blocking: A 3-tuple of (returncode, stdout, stderr); If non-blocking - A subprocess.Popen object for the shell process. """ sh = create_shell(shell) if hasattr(command, "__iter__"): command = sh.join(command) # start a new session if specified if start_new_session: Popen_args.update(config.new_session_popen_args) # open a separate terminal if specified if detached: term_cmd = config.terminal_emulator_command if term_cmd: pre_command = term_cmd.strip().split() # block if the shell is likely to be interactive if block is None: block = not (command or stdin) # context and rxt files. If running detached, don't cleanup files, because # rez-env returns too early and deletes the tmp files before the detached # process can use them tmpdir = self.tmpdir_manager.mkdtemp(cleanup=not detached) if self.load_path and os.path.isfile(self.load_path): rxt_file = self.load_path else: rxt_file = os.path.join(tmpdir, "context.rxt") self.save(rxt_file) context_file = context_filepath or \ os.path.join(tmpdir, "context.%s" % sh.file_extension()) # interpret this context and write out the native context file executor = self._create_executor(sh, parent_environ) executor.env.REZ_RXT_FILE = rxt_file executor.env.REZ_CONTEXT_FILE = context_file if actions_callback: actions_callback(executor) self._execute(executor) if post_actions_callback: post_actions_callback(executor) context_code = executor.get_output() with open(context_file, 'w') as f: f.write(context_code) quiet = quiet or \ (RezToolsVisibility[config.rez_tools_visibility] == RezToolsVisibility.never) # spawn the shell subprocess p = sh.spawn_shell(context_file, tmpdir, rcfile=rcfile, norc=norc, stdin=stdin, command=command, env=parent_environ, quiet=quiet, pre_command=pre_command, **Popen_args) if block: stdout, stderr = p.communicate() return p.returncode, stdout, stderr else: return p
[ "def", "execute_shell", "(", "self", ",", "shell", "=", "None", ",", "parent_environ", "=", "None", ",", "rcfile", "=", "None", ",", "norc", "=", "False", ",", "stdin", "=", "False", ",", "command", "=", "None", ",", "quiet", "=", "False", ",", "block", "=", "None", ",", "actions_callback", "=", "None", ",", "post_actions_callback", "=", "None", ",", "context_filepath", "=", "None", ",", "start_new_session", "=", "False", ",", "detached", "=", "False", ",", "pre_command", "=", "None", ",", "*", "*", "Popen_args", ")", ":", "sh", "=", "create_shell", "(", "shell", ")", "if", "hasattr", "(", "command", ",", "\"__iter__\"", ")", ":", "command", "=", "sh", ".", "join", "(", "command", ")", "# start a new session if specified", "if", "start_new_session", ":", "Popen_args", ".", "update", "(", "config", ".", "new_session_popen_args", ")", "# open a separate terminal if specified", "if", "detached", ":", "term_cmd", "=", "config", ".", "terminal_emulator_command", "if", "term_cmd", ":", "pre_command", "=", "term_cmd", ".", "strip", "(", ")", ".", "split", "(", ")", "# block if the shell is likely to be interactive", "if", "block", "is", "None", ":", "block", "=", "not", "(", "command", "or", "stdin", ")", "# context and rxt files. If running detached, don't cleanup files, because", "# rez-env returns too early and deletes the tmp files before the detached", "# process can use them", "tmpdir", "=", "self", ".", "tmpdir_manager", ".", "mkdtemp", "(", "cleanup", "=", "not", "detached", ")", "if", "self", ".", "load_path", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "load_path", ")", ":", "rxt_file", "=", "self", ".", "load_path", "else", ":", "rxt_file", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"context.rxt\"", ")", "self", ".", "save", "(", "rxt_file", ")", "context_file", "=", "context_filepath", "or", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"context.%s\"", "%", "sh", ".", "file_extension", "(", ")", ")", "# interpret this context and write out the native context file", "executor", "=", "self", ".", "_create_executor", "(", "sh", ",", "parent_environ", ")", "executor", ".", "env", ".", "REZ_RXT_FILE", "=", "rxt_file", "executor", ".", "env", ".", "REZ_CONTEXT_FILE", "=", "context_file", "if", "actions_callback", ":", "actions_callback", "(", "executor", ")", "self", ".", "_execute", "(", "executor", ")", "if", "post_actions_callback", ":", "post_actions_callback", "(", "executor", ")", "context_code", "=", "executor", ".", "get_output", "(", ")", "with", "open", "(", "context_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "context_code", ")", "quiet", "=", "quiet", "or", "(", "RezToolsVisibility", "[", "config", ".", "rez_tools_visibility", "]", "==", "RezToolsVisibility", ".", "never", ")", "# spawn the shell subprocess", "p", "=", "sh", ".", "spawn_shell", "(", "context_file", ",", "tmpdir", ",", "rcfile", "=", "rcfile", ",", "norc", "=", "norc", ",", "stdin", "=", "stdin", ",", "command", "=", "command", ",", "env", "=", "parent_environ", ",", "quiet", "=", "quiet", ",", "pre_command", "=", "pre_command", ",", "*", "*", "Popen_args", ")", "if", "block", ":", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "return", "p", ".", "returncode", ",", "stdout", ",", "stderr", "else", ":", "return", "p" ]
Spawn a possibly-interactive shell. Args: shell: Shell type, for eg 'bash'. If None, the current shell type is used. parent_environ: Environment to run the shell process in, if None then the current environment is used. rcfile: Specify a file to source instead of shell startup files. norc: If True, skip shell startup files, if possible. stdin: If True, read commands from stdin, in a non-interactive shell. command: If not None, execute this command in a non-interactive shell. If an empty string or list, don't run a command, but don't open an interactive shell either. Can be a list of args. quiet: If True, skip the welcome message in interactive shells. block: If True, block until the shell is terminated. If False, return immediately. If None, will default to blocking if the shell is interactive. actions_callback: Callback with signature (RexExecutor). This lets the user append custom actions to the context, such as setting extra environment variables. Callback is run prior to context Rex execution. post_actions_callback: Callback with signature (RexExecutor). This lets the user append custom actions to the context, such as setting extra environment variables. Callback is run after context Rex execution. context_filepath: If provided, the context file will be written here, rather than to the default location (which is in a tempdir). If you use this arg, you are responsible for cleaning up the file. start_new_session: If True, change the process group of the target process. Note that this may override the Popen_args keyword 'preexec_fn'. detached: If True, open a separate terminal. Note that this may override the `pre_command` argument. pre_command: Command to inject before the shell command itself. This is for internal use. Popen_args: args to pass to the shell process object constructor. Returns: If blocking: A 3-tuple of (returncode, stdout, stderr); If non-blocking - A subprocess.Popen object for the shell process.
[ "Spawn", "a", "possibly", "-", "interactive", "shell", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1156-L1272
232,661
nerdvegas/rez
src/rez/resolved_context.py
ResolvedContext.to_dict
def to_dict(self, fields=None): """Convert context to dict containing only builtin types. Args: fields (list of str): If present, only write these fields into the dict. This can be used to avoid constructing expensive fields (such as 'graph') for some cases. Returns: dict: Dictified context. """ data = {} def _add(field): return (fields is None or field in fields) if _add("resolved_packages"): resolved_packages = [] for pkg in (self._resolved_packages or []): resolved_packages.append(pkg.handle.to_dict()) data["resolved_packages"] = resolved_packages if _add("serialize_version"): data["serialize_version"] = \ '.'.join(map(str, ResolvedContext.serialize_version)) if _add("patch_locks"): data["patch_locks"] = dict((k, v.name) for k, v in self.patch_locks) if _add("package_orderers"): package_orderers = [package_order.to_pod(x) for x in (self.package_orderers or [])] data["package_orderers"] = package_orderers or None if _add("package_filter"): data["package_filter"] = self.package_filter.to_pod() if _add("graph"): if self.graph_string and self.graph_string.startswith('{'): graph_str = self.graph_string # already in compact format else: g = self.graph() graph_str = write_compacted(g) data["graph"] = graph_str data.update(dict( timestamp=self.timestamp, requested_timestamp=self.requested_timestamp, building=self.building, caching=self.caching, implicit_packages=map(str, self.implicit_packages), package_requests=map(str, self._package_requests), package_paths=self.package_paths, default_patch_lock=self.default_patch_lock.name, rez_version=self.rez_version, rez_path=self.rez_path, user=self.user, host=self.host, platform=self.platform, arch=self.arch, os=self.os, created=self.created, parent_suite_path=self.parent_suite_path, suite_context_name=self.suite_context_name, status=self.status_.name, failure_description=self.failure_description, from_cache=self.from_cache, solve_time=self.solve_time, load_time=self.load_time, num_loaded_packages=self.num_loaded_packages )) if fields: data = dict((k, v) for k, v in data.iteritems() if k in fields) return data
python
def to_dict(self, fields=None): """Convert context to dict containing only builtin types. Args: fields (list of str): If present, only write these fields into the dict. This can be used to avoid constructing expensive fields (such as 'graph') for some cases. Returns: dict: Dictified context. """ data = {} def _add(field): return (fields is None or field in fields) if _add("resolved_packages"): resolved_packages = [] for pkg in (self._resolved_packages or []): resolved_packages.append(pkg.handle.to_dict()) data["resolved_packages"] = resolved_packages if _add("serialize_version"): data["serialize_version"] = \ '.'.join(map(str, ResolvedContext.serialize_version)) if _add("patch_locks"): data["patch_locks"] = dict((k, v.name) for k, v in self.patch_locks) if _add("package_orderers"): package_orderers = [package_order.to_pod(x) for x in (self.package_orderers or [])] data["package_orderers"] = package_orderers or None if _add("package_filter"): data["package_filter"] = self.package_filter.to_pod() if _add("graph"): if self.graph_string and self.graph_string.startswith('{'): graph_str = self.graph_string # already in compact format else: g = self.graph() graph_str = write_compacted(g) data["graph"] = graph_str data.update(dict( timestamp=self.timestamp, requested_timestamp=self.requested_timestamp, building=self.building, caching=self.caching, implicit_packages=map(str, self.implicit_packages), package_requests=map(str, self._package_requests), package_paths=self.package_paths, default_patch_lock=self.default_patch_lock.name, rez_version=self.rez_version, rez_path=self.rez_path, user=self.user, host=self.host, platform=self.platform, arch=self.arch, os=self.os, created=self.created, parent_suite_path=self.parent_suite_path, suite_context_name=self.suite_context_name, status=self.status_.name, failure_description=self.failure_description, from_cache=self.from_cache, solve_time=self.solve_time, load_time=self.load_time, num_loaded_packages=self.num_loaded_packages )) if fields: data = dict((k, v) for k, v in data.iteritems() if k in fields) return data
[ "def", "to_dict", "(", "self", ",", "fields", "=", "None", ")", ":", "data", "=", "{", "}", "def", "_add", "(", "field", ")", ":", "return", "(", "fields", "is", "None", "or", "field", "in", "fields", ")", "if", "_add", "(", "\"resolved_packages\"", ")", ":", "resolved_packages", "=", "[", "]", "for", "pkg", "in", "(", "self", ".", "_resolved_packages", "or", "[", "]", ")", ":", "resolved_packages", ".", "append", "(", "pkg", ".", "handle", ".", "to_dict", "(", ")", ")", "data", "[", "\"resolved_packages\"", "]", "=", "resolved_packages", "if", "_add", "(", "\"serialize_version\"", ")", ":", "data", "[", "\"serialize_version\"", "]", "=", "'.'", ".", "join", "(", "map", "(", "str", ",", "ResolvedContext", ".", "serialize_version", ")", ")", "if", "_add", "(", "\"patch_locks\"", ")", ":", "data", "[", "\"patch_locks\"", "]", "=", "dict", "(", "(", "k", ",", "v", ".", "name", ")", "for", "k", ",", "v", "in", "self", ".", "patch_locks", ")", "if", "_add", "(", "\"package_orderers\"", ")", ":", "package_orderers", "=", "[", "package_order", ".", "to_pod", "(", "x", ")", "for", "x", "in", "(", "self", ".", "package_orderers", "or", "[", "]", ")", "]", "data", "[", "\"package_orderers\"", "]", "=", "package_orderers", "or", "None", "if", "_add", "(", "\"package_filter\"", ")", ":", "data", "[", "\"package_filter\"", "]", "=", "self", ".", "package_filter", ".", "to_pod", "(", ")", "if", "_add", "(", "\"graph\"", ")", ":", "if", "self", ".", "graph_string", "and", "self", ".", "graph_string", ".", "startswith", "(", "'{'", ")", ":", "graph_str", "=", "self", ".", "graph_string", "# already in compact format", "else", ":", "g", "=", "self", ".", "graph", "(", ")", "graph_str", "=", "write_compacted", "(", "g", ")", "data", "[", "\"graph\"", "]", "=", "graph_str", "data", ".", "update", "(", "dict", "(", "timestamp", "=", "self", ".", "timestamp", ",", "requested_timestamp", "=", "self", ".", "requested_timestamp", ",", "building", "=", "self", ".", "building", ",", "caching", "=", "self", ".", "caching", ",", "implicit_packages", "=", "map", "(", "str", ",", "self", ".", "implicit_packages", ")", ",", "package_requests", "=", "map", "(", "str", ",", "self", ".", "_package_requests", ")", ",", "package_paths", "=", "self", ".", "package_paths", ",", "default_patch_lock", "=", "self", ".", "default_patch_lock", ".", "name", ",", "rez_version", "=", "self", ".", "rez_version", ",", "rez_path", "=", "self", ".", "rez_path", ",", "user", "=", "self", ".", "user", ",", "host", "=", "self", ".", "host", ",", "platform", "=", "self", ".", "platform", ",", "arch", "=", "self", ".", "arch", ",", "os", "=", "self", ".", "os", ",", "created", "=", "self", ".", "created", ",", "parent_suite_path", "=", "self", ".", "parent_suite_path", ",", "suite_context_name", "=", "self", ".", "suite_context_name", ",", "status", "=", "self", ".", "status_", ".", "name", ",", "failure_description", "=", "self", ".", "failure_description", ",", "from_cache", "=", "self", ".", "from_cache", ",", "solve_time", "=", "self", ".", "solve_time", ",", "load_time", "=", "self", ".", "load_time", ",", "num_loaded_packages", "=", "self", ".", "num_loaded_packages", ")", ")", "if", "fields", ":", "data", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "data", ".", "iteritems", "(", ")", "if", "k", "in", "fields", ")", "return", "data" ]
Convert context to dict containing only builtin types. Args: fields (list of str): If present, only write these fields into the dict. This can be used to avoid constructing expensive fields (such as 'graph') for some cases. Returns: dict: Dictified context.
[ "Convert", "context", "to", "dict", "containing", "only", "builtin", "types", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L1274-L1355
232,662
nerdvegas/rez
src/rez/utils/system.py
add_sys_paths
def add_sys_paths(paths): """Add to sys.path, and revert on scope exit. """ original_syspath = sys.path[:] sys.path.extend(paths) try: yield finally: sys.path = original_syspath
python
def add_sys_paths(paths): """Add to sys.path, and revert on scope exit. """ original_syspath = sys.path[:] sys.path.extend(paths) try: yield finally: sys.path = original_syspath
[ "def", "add_sys_paths", "(", "paths", ")", ":", "original_syspath", "=", "sys", ".", "path", "[", ":", "]", "sys", ".", "path", ".", "extend", "(", "paths", ")", "try", ":", "yield", "finally", ":", "sys", ".", "path", "=", "original_syspath" ]
Add to sys.path, and revert on scope exit.
[ "Add", "to", "sys", ".", "path", "and", "revert", "on", "scope", "exit", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/system.py#L7-L16
232,663
nerdvegas/rez
src/rez/utils/system.py
popen
def popen(args, **kwargs): """Wrapper for `subprocess.Popen`. Avoids python bug described here: https://bugs.python.org/issue3905. This can arise when apps (maya) install a non-standard stdin handler. In newer version of maya and katana, the sys.stdin object can also become replaced by an object with no 'fileno' attribute, this is also taken into account. """ if "stdin" not in kwargs: try: file_no = sys.stdin.fileno() except AttributeError: file_no = sys.__stdin__.fileno() if file_no not in (0, 1, 2): kwargs["stdin"] = subprocess.PIPE return subprocess.Popen(args, **kwargs)
python
def popen(args, **kwargs): """Wrapper for `subprocess.Popen`. Avoids python bug described here: https://bugs.python.org/issue3905. This can arise when apps (maya) install a non-standard stdin handler. In newer version of maya and katana, the sys.stdin object can also become replaced by an object with no 'fileno' attribute, this is also taken into account. """ if "stdin" not in kwargs: try: file_no = sys.stdin.fileno() except AttributeError: file_no = sys.__stdin__.fileno() if file_no not in (0, 1, 2): kwargs["stdin"] = subprocess.PIPE return subprocess.Popen(args, **kwargs)
[ "def", "popen", "(", "args", ",", "*", "*", "kwargs", ")", ":", "if", "\"stdin\"", "not", "in", "kwargs", ":", "try", ":", "file_no", "=", "sys", ".", "stdin", ".", "fileno", "(", ")", "except", "AttributeError", ":", "file_no", "=", "sys", ".", "__stdin__", ".", "fileno", "(", ")", "if", "file_no", "not", "in", "(", "0", ",", "1", ",", "2", ")", ":", "kwargs", "[", "\"stdin\"", "]", "=", "subprocess", ".", "PIPE", "return", "subprocess", ".", "Popen", "(", "args", ",", "*", "*", "kwargs", ")" ]
Wrapper for `subprocess.Popen`. Avoids python bug described here: https://bugs.python.org/issue3905. This can arise when apps (maya) install a non-standard stdin handler. In newer version of maya and katana, the sys.stdin object can also become replaced by an object with no 'fileno' attribute, this is also taken into account.
[ "Wrapper", "for", "subprocess", ".", "Popen", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/system.py#L19-L38
232,664
nerdvegas/rez
src/rezplugins/release_vcs/git.py
GitReleaseVCS.get_relative_to_remote
def get_relative_to_remote(self): """Return the number of commits we are relative to the remote. Negative is behind, positive in front, zero means we are matched to remote. """ s = self.git("status", "--short", "-b")[0] r = re.compile("\[([^\]]+)\]") toks = r.findall(s) if toks: try: s2 = toks[-1] adj, n = s2.split() assert(adj in ("ahead", "behind")) n = int(n) return -n if adj == "behind" else n except Exception as e: raise ReleaseVCSError( ("Problem parsing first line of result of 'git status " "--short -b' (%s):\n%s") % (s, str(e))) else: return 0
python
def get_relative_to_remote(self): """Return the number of commits we are relative to the remote. Negative is behind, positive in front, zero means we are matched to remote. """ s = self.git("status", "--short", "-b")[0] r = re.compile("\[([^\]]+)\]") toks = r.findall(s) if toks: try: s2 = toks[-1] adj, n = s2.split() assert(adj in ("ahead", "behind")) n = int(n) return -n if adj == "behind" else n except Exception as e: raise ReleaseVCSError( ("Problem parsing first line of result of 'git status " "--short -b' (%s):\n%s") % (s, str(e))) else: return 0
[ "def", "get_relative_to_remote", "(", "self", ")", ":", "s", "=", "self", ".", "git", "(", "\"status\"", ",", "\"--short\"", ",", "\"-b\"", ")", "[", "0", "]", "r", "=", "re", ".", "compile", "(", "\"\\[([^\\]]+)\\]\"", ")", "toks", "=", "r", ".", "findall", "(", "s", ")", "if", "toks", ":", "try", ":", "s2", "=", "toks", "[", "-", "1", "]", "adj", ",", "n", "=", "s2", ".", "split", "(", ")", "assert", "(", "adj", "in", "(", "\"ahead\"", ",", "\"behind\"", ")", ")", "n", "=", "int", "(", "n", ")", "return", "-", "n", "if", "adj", "==", "\"behind\"", "else", "n", "except", "Exception", "as", "e", ":", "raise", "ReleaseVCSError", "(", "(", "\"Problem parsing first line of result of 'git status \"", "\"--short -b' (%s):\\n%s\"", ")", "%", "(", "s", ",", "str", "(", "e", ")", ")", ")", "else", ":", "return", "0" ]
Return the number of commits we are relative to the remote. Negative is behind, positive in front, zero means we are matched to remote.
[ "Return", "the", "number", "of", "commits", "we", "are", "relative", "to", "the", "remote", ".", "Negative", "is", "behind", "positive", "in", "front", "zero", "means", "we", "are", "matched", "to", "remote", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/git.py#L47-L66
232,665
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.links
def links(self, obj): """ Return all nodes connected by the given hyperedge or all hyperedges connected to the given hypernode. @type obj: hyperedge @param obj: Object identifier. @rtype: list @return: List of node objects linked to the given hyperedge. """ if obj in self.edge_links: return self.edge_links[obj] else: return self.node_links[obj]
python
def links(self, obj): """ Return all nodes connected by the given hyperedge or all hyperedges connected to the given hypernode. @type obj: hyperedge @param obj: Object identifier. @rtype: list @return: List of node objects linked to the given hyperedge. """ if obj in self.edge_links: return self.edge_links[obj] else: return self.node_links[obj]
[ "def", "links", "(", "self", ",", "obj", ")", ":", "if", "obj", "in", "self", ".", "edge_links", ":", "return", "self", ".", "edge_links", "[", "obj", "]", "else", ":", "return", "self", ".", "node_links", "[", "obj", "]" ]
Return all nodes connected by the given hyperedge or all hyperedges connected to the given hypernode. @type obj: hyperedge @param obj: Object identifier. @rtype: list @return: List of node objects linked to the given hyperedge.
[ "Return", "all", "nodes", "connected", "by", "the", "given", "hyperedge", "or", "all", "hyperedges", "connected", "to", "the", "given", "hypernode", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L122-L136
232,666
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.neighbors
def neighbors(self, obj): """ Return all neighbors adjacent to the given node. @type obj: node @param obj: Object identifier. @rtype: list @return: List of all node objects adjacent to the given node. """ neighbors = set([]) for e in self.node_links[obj]: neighbors.update(set(self.edge_links[e])) return list(neighbors - set([obj]))
python
def neighbors(self, obj): """ Return all neighbors adjacent to the given node. @type obj: node @param obj: Object identifier. @rtype: list @return: List of all node objects adjacent to the given node. """ neighbors = set([]) for e in self.node_links[obj]: neighbors.update(set(self.edge_links[e])) return list(neighbors - set([obj]))
[ "def", "neighbors", "(", "self", ",", "obj", ")", ":", "neighbors", "=", "set", "(", "[", "]", ")", "for", "e", "in", "self", ".", "node_links", "[", "obj", "]", ":", "neighbors", ".", "update", "(", "set", "(", "self", ".", "edge_links", "[", "e", "]", ")", ")", "return", "list", "(", "neighbors", "-", "set", "(", "[", "obj", "]", ")", ")" ]
Return all neighbors adjacent to the given node. @type obj: node @param obj: Object identifier. @rtype: list @return: List of all node objects adjacent to the given node.
[ "Return", "all", "neighbors", "adjacent", "to", "the", "given", "node", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L139-L154
232,667
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.del_node
def del_node(self, node): """ Delete a given node from the hypergraph. @type node: node @param node: Node identifier. """ if self.has_node(node): for e in self.node_links[node]: self.edge_links[e].remove(node) self.node_links.pop(node) self.graph.del_node((node,'n'))
python
def del_node(self, node): """ Delete a given node from the hypergraph. @type node: node @param node: Node identifier. """ if self.has_node(node): for e in self.node_links[node]: self.edge_links[e].remove(node) self.node_links.pop(node) self.graph.del_node((node,'n'))
[ "def", "del_node", "(", "self", ",", "node", ")", ":", "if", "self", ".", "has_node", "(", "node", ")", ":", "for", "e", "in", "self", ".", "node_links", "[", "node", "]", ":", "self", ".", "edge_links", "[", "e", "]", ".", "remove", "(", "node", ")", "self", ".", "node_links", ".", "pop", "(", "node", ")", "self", ".", "graph", ".", "del_node", "(", "(", "node", ",", "'n'", ")", ")" ]
Delete a given node from the hypergraph. @type node: node @param node: Node identifier.
[ "Delete", "a", "given", "node", "from", "the", "hypergraph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L188-L200
232,668
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.add_hyperedge
def add_hyperedge(self, hyperedge): """ Add given hyperedge to the hypergraph. @attention: While hyperedge-nodes can be of any type, it's strongly recommended to use only numbers and single-line strings as node identifiers if you intend to use write(). @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier. """ if (not hyperedge in self.edge_links): self.edge_links[hyperedge] = [] self.graph.add_node((hyperedge,'h'))
python
def add_hyperedge(self, hyperedge): """ Add given hyperedge to the hypergraph. @attention: While hyperedge-nodes can be of any type, it's strongly recommended to use only numbers and single-line strings as node identifiers if you intend to use write(). @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier. """ if (not hyperedge in self.edge_links): self.edge_links[hyperedge] = [] self.graph.add_node((hyperedge,'h'))
[ "def", "add_hyperedge", "(", "self", ",", "hyperedge", ")", ":", "if", "(", "not", "hyperedge", "in", "self", ".", "edge_links", ")", ":", "self", ".", "edge_links", "[", "hyperedge", "]", "=", "[", "]", "self", ".", "graph", ".", "add_node", "(", "(", "hyperedge", ",", "'h'", ")", ")" ]
Add given hyperedge to the hypergraph. @attention: While hyperedge-nodes can be of any type, it's strongly recommended to use only numbers and single-line strings as node identifiers if you intend to use write(). @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier.
[ "Add", "given", "hyperedge", "to", "the", "hypergraph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L216-L228
232,669
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.del_hyperedge
def del_hyperedge(self, hyperedge): """ Delete the given hyperedge. @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier. """ if (hyperedge in self.hyperedges()): for n in self.edge_links[hyperedge]: self.node_links[n].remove(hyperedge) del(self.edge_links[hyperedge]) self.del_edge_labeling(hyperedge) self.graph.del_node((hyperedge,'h'))
python
def del_hyperedge(self, hyperedge): """ Delete the given hyperedge. @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier. """ if (hyperedge in self.hyperedges()): for n in self.edge_links[hyperedge]: self.node_links[n].remove(hyperedge) del(self.edge_links[hyperedge]) self.del_edge_labeling(hyperedge) self.graph.del_node((hyperedge,'h'))
[ "def", "del_hyperedge", "(", "self", ",", "hyperedge", ")", ":", "if", "(", "hyperedge", "in", "self", ".", "hyperedges", "(", ")", ")", ":", "for", "n", "in", "self", ".", "edge_links", "[", "hyperedge", "]", ":", "self", ".", "node_links", "[", "n", "]", ".", "remove", "(", "hyperedge", ")", "del", "(", "self", ".", "edge_links", "[", "hyperedge", "]", ")", "self", ".", "del_edge_labeling", "(", "hyperedge", ")", "self", ".", "graph", ".", "del_node", "(", "(", "hyperedge", ",", "'h'", ")", ")" ]
Delete the given hyperedge. @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier.
[ "Delete", "the", "given", "hyperedge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L268-L281
232,670
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.link
def link(self, node, hyperedge): """ Link given node and hyperedge. @type node: node @param node: Node. @type hyperedge: node @param hyperedge: Hyperedge. """ if (hyperedge not in self.node_links[node]): self.edge_links[hyperedge].append(node) self.node_links[node].append(hyperedge) self.graph.add_edge(((node,'n'), (hyperedge,'h'))) else: raise AdditionError("Link (%s, %s) already in graph" % (node, hyperedge))
python
def link(self, node, hyperedge): """ Link given node and hyperedge. @type node: node @param node: Node. @type hyperedge: node @param hyperedge: Hyperedge. """ if (hyperedge not in self.node_links[node]): self.edge_links[hyperedge].append(node) self.node_links[node].append(hyperedge) self.graph.add_edge(((node,'n'), (hyperedge,'h'))) else: raise AdditionError("Link (%s, %s) already in graph" % (node, hyperedge))
[ "def", "link", "(", "self", ",", "node", ",", "hyperedge", ")", ":", "if", "(", "hyperedge", "not", "in", "self", ".", "node_links", "[", "node", "]", ")", ":", "self", ".", "edge_links", "[", "hyperedge", "]", ".", "append", "(", "node", ")", "self", ".", "node_links", "[", "node", "]", ".", "append", "(", "hyperedge", ")", "self", ".", "graph", ".", "add_edge", "(", "(", "(", "node", ",", "'n'", ")", ",", "(", "hyperedge", ",", "'h'", ")", ")", ")", "else", ":", "raise", "AdditionError", "(", "\"Link (%s, %s) already in graph\"", "%", "(", "node", ",", "hyperedge", ")", ")" ]
Link given node and hyperedge. @type node: node @param node: Node. @type hyperedge: node @param hyperedge: Hyperedge.
[ "Link", "given", "node", "and", "hyperedge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L284-L299
232,671
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.unlink
def unlink(self, node, hyperedge): """ Unlink given node and hyperedge. @type node: node @param node: Node. @type hyperedge: hyperedge @param hyperedge: Hyperedge. """ self.node_links[node].remove(hyperedge) self.edge_links[hyperedge].remove(node) self.graph.del_edge(((node,'n'), (hyperedge,'h')))
python
def unlink(self, node, hyperedge): """ Unlink given node and hyperedge. @type node: node @param node: Node. @type hyperedge: hyperedge @param hyperedge: Hyperedge. """ self.node_links[node].remove(hyperedge) self.edge_links[hyperedge].remove(node) self.graph.del_edge(((node,'n'), (hyperedge,'h')))
[ "def", "unlink", "(", "self", ",", "node", ",", "hyperedge", ")", ":", "self", ".", "node_links", "[", "node", "]", ".", "remove", "(", "hyperedge", ")", "self", ".", "edge_links", "[", "hyperedge", "]", ".", "remove", "(", "node", ")", "self", ".", "graph", ".", "del_edge", "(", "(", "(", "node", ",", "'n'", ")", ",", "(", "hyperedge", ",", "'h'", ")", ")", ")" ]
Unlink given node and hyperedge. @type node: node @param node: Node. @type hyperedge: hyperedge @param hyperedge: Hyperedge.
[ "Unlink", "given", "node", "and", "hyperedge", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L302-L314
232,672
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
hypergraph.rank
def rank(self): """ Return the rank of the given hypergraph. @rtype: int @return: Rank of graph. """ max_rank = 0 for each in self.hyperedges(): if len(self.edge_links[each]) > max_rank: max_rank = len(self.edge_links[each]) return max_rank
python
def rank(self): """ Return the rank of the given hypergraph. @rtype: int @return: Rank of graph. """ max_rank = 0 for each in self.hyperedges(): if len(self.edge_links[each]) > max_rank: max_rank = len(self.edge_links[each]) return max_rank
[ "def", "rank", "(", "self", ")", ":", "max_rank", "=", "0", "for", "each", "in", "self", ".", "hyperedges", "(", ")", ":", "if", "len", "(", "self", ".", "edge_links", "[", "each", "]", ")", ">", "max_rank", ":", "max_rank", "=", "len", "(", "self", ".", "edge_links", "[", "each", "]", ")", "return", "max_rank" ]
Return the rank of the given hypergraph. @rtype: int @return: Rank of graph.
[ "Return", "the", "rank", "of", "the", "given", "hypergraph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L317-L330
232,673
nerdvegas/rez
src/rez/utils/base26.py
get_next_base26
def get_next_base26(prev=None): """Increment letter-based IDs. Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...] Returns: str: Next base-26 ID. """ if not prev: return 'a' r = re.compile("^[a-z]*$") if not r.match(prev): raise ValueError("Invalid base26") if not prev.endswith('z'): return prev[:-1] + chr(ord(prev[-1]) + 1) return get_next_base26(prev[:-1]) + 'a'
python
def get_next_base26(prev=None): """Increment letter-based IDs. Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...] Returns: str: Next base-26 ID. """ if not prev: return 'a' r = re.compile("^[a-z]*$") if not r.match(prev): raise ValueError("Invalid base26") if not prev.endswith('z'): return prev[:-1] + chr(ord(prev[-1]) + 1) return get_next_base26(prev[:-1]) + 'a'
[ "def", "get_next_base26", "(", "prev", "=", "None", ")", ":", "if", "not", "prev", ":", "return", "'a'", "r", "=", "re", ".", "compile", "(", "\"^[a-z]*$\"", ")", "if", "not", "r", ".", "match", "(", "prev", ")", ":", "raise", "ValueError", "(", "\"Invalid base26\"", ")", "if", "not", "prev", ".", "endswith", "(", "'z'", ")", ":", "return", "prev", "[", ":", "-", "1", "]", "+", "chr", "(", "ord", "(", "prev", "[", "-", "1", "]", ")", "+", "1", ")", "return", "get_next_base26", "(", "prev", "[", ":", "-", "1", "]", ")", "+", "'a'" ]
Increment letter-based IDs. Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...] Returns: str: Next base-26 ID.
[ "Increment", "letter", "-", "based", "IDs", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/base26.py#L9-L27
232,674
nerdvegas/rez
src/rez/utils/base26.py
create_unique_base26_symlink
def create_unique_base26_symlink(path, source): """Create a base-26 symlink in `path` pointing to `source`. If such a symlink already exists, it is returned. Note that there is a small chance that this function may create a new symlink when there is already one pointed at `source`. Assumes `path` only contains base26 symlinks. Returns: str: Path to created symlink. """ retries = 0 while True: # if a link already exists that points at `source`, return it name = find_matching_symlink(path, source) if name: return os.path.join(path, name) # get highest current symlink in path names = [ x for x in os.listdir(path) if os.path.islink(os.path.join(path, x)) ] if names: prev = max(names) else: prev = None linkname = get_next_base26(prev) linkpath = os.path.join(path, linkname) # attempt to create the symlink try: os.symlink(source, linkpath) return linkpath except OSError as e: if e.errno != errno.EEXIST: raise # if we're here, the same named symlink was created in parallel # somewhere. Try again up to N times. # if retries > 10: raise RuntimeError( "Variant shortlink not created - there was too much contention.") retries += 1
python
def create_unique_base26_symlink(path, source): """Create a base-26 symlink in `path` pointing to `source`. If such a symlink already exists, it is returned. Note that there is a small chance that this function may create a new symlink when there is already one pointed at `source`. Assumes `path` only contains base26 symlinks. Returns: str: Path to created symlink. """ retries = 0 while True: # if a link already exists that points at `source`, return it name = find_matching_symlink(path, source) if name: return os.path.join(path, name) # get highest current symlink in path names = [ x for x in os.listdir(path) if os.path.islink(os.path.join(path, x)) ] if names: prev = max(names) else: prev = None linkname = get_next_base26(prev) linkpath = os.path.join(path, linkname) # attempt to create the symlink try: os.symlink(source, linkpath) return linkpath except OSError as e: if e.errno != errno.EEXIST: raise # if we're here, the same named symlink was created in parallel # somewhere. Try again up to N times. # if retries > 10: raise RuntimeError( "Variant shortlink not created - there was too much contention.") retries += 1
[ "def", "create_unique_base26_symlink", "(", "path", ",", "source", ")", ":", "retries", "=", "0", "while", "True", ":", "# if a link already exists that points at `source`, return it", "name", "=", "find_matching_symlink", "(", "path", ",", "source", ")", "if", "name", ":", "return", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "# get highest current symlink in path", "names", "=", "[", "x", "for", "x", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "islink", "(", "os", ".", "path", ".", "join", "(", "path", ",", "x", ")", ")", "]", "if", "names", ":", "prev", "=", "max", "(", "names", ")", "else", ":", "prev", "=", "None", "linkname", "=", "get_next_base26", "(", "prev", ")", "linkpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "linkname", ")", "# attempt to create the symlink", "try", ":", "os", ".", "symlink", "(", "source", ",", "linkpath", ")", "return", "linkpath", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "# if we're here, the same named symlink was created in parallel", "# somewhere. Try again up to N times.", "#", "if", "retries", ">", "10", ":", "raise", "RuntimeError", "(", "\"Variant shortlink not created - there was too much contention.\"", ")", "retries", "+=", "1" ]
Create a base-26 symlink in `path` pointing to `source`. If such a symlink already exists, it is returned. Note that there is a small chance that this function may create a new symlink when there is already one pointed at `source`. Assumes `path` only contains base26 symlinks. Returns: str: Path to created symlink.
[ "Create", "a", "base", "-", "26", "symlink", "in", "path", "pointing", "to", "source", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/base26.py#L30-L79
232,675
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
find_wheels
def find_wheels(projects, search_dirs): """Find wheels from which we can import PROJECTS. Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return a list of the first wheel found for each PROJECT """ wheels = [] # Look through SEARCH_DIRS for the first suitable wheel. Don't bother # about version checking here, as this is simply to get something we can # then use to install the correct version. for project in projects: for dirname in search_dirs: # This relies on only having "universal" wheels available. # The pattern could be tightened to require -py2.py3-none-any.whl. files = glob.glob(os.path.join(dirname, project + '-*.whl')) if files: wheels.append(os.path.abspath(files[0])) break else: # We're out of luck, so quit with a suitable error logger.fatal('Cannot find a wheel for %s' % (project,)) return wheels
python
def find_wheels(projects, search_dirs): """Find wheels from which we can import PROJECTS. Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return a list of the first wheel found for each PROJECT """ wheels = [] # Look through SEARCH_DIRS for the first suitable wheel. Don't bother # about version checking here, as this is simply to get something we can # then use to install the correct version. for project in projects: for dirname in search_dirs: # This relies on only having "universal" wheels available. # The pattern could be tightened to require -py2.py3-none-any.whl. files = glob.glob(os.path.join(dirname, project + '-*.whl')) if files: wheels.append(os.path.abspath(files[0])) break else: # We're out of luck, so quit with a suitable error logger.fatal('Cannot find a wheel for %s' % (project,)) return wheels
[ "def", "find_wheels", "(", "projects", ",", "search_dirs", ")", ":", "wheels", "=", "[", "]", "# Look through SEARCH_DIRS for the first suitable wheel. Don't bother", "# about version checking here, as this is simply to get something we can", "# then use to install the correct version.", "for", "project", "in", "projects", ":", "for", "dirname", "in", "search_dirs", ":", "# This relies on only having \"universal\" wheels available.", "# The pattern could be tightened to require -py2.py3-none-any.whl.", "files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "dirname", ",", "project", "+", "'-*.whl'", ")", ")", "if", "files", ":", "wheels", ".", "append", "(", "os", ".", "path", ".", "abspath", "(", "files", "[", "0", "]", ")", ")", "break", "else", ":", "# We're out of luck, so quit with a suitable error", "logger", ".", "fatal", "(", "'Cannot find a wheel for %s'", "%", "(", "project", ",", ")", ")", "return", "wheels" ]
Find wheels from which we can import PROJECTS. Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return a list of the first wheel found for each PROJECT
[ "Find", "wheels", "from", "which", "we", "can", "import", "PROJECTS", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L913-L937
232,676
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
relative_script
def relative_script(lines): "Return a script that'll work in a relocatable environment." activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this" # Find the last future statement in the script. If we insert the activation # line before a future statement, Python will raise a SyntaxError. activate_at = None for idx, line in reversed(list(enumerate(lines))): if line.split()[:3] == ['from', '__future__', 'import']: activate_at = idx + 1 break if activate_at is None: # Activate after the shebang. activate_at = 1 return lines[:activate_at] + ['', activate, ''] + lines[activate_at:]
python
def relative_script(lines): "Return a script that'll work in a relocatable environment." activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this" # Find the last future statement in the script. If we insert the activation # line before a future statement, Python will raise a SyntaxError. activate_at = None for idx, line in reversed(list(enumerate(lines))): if line.split()[:3] == ['from', '__future__', 'import']: activate_at = idx + 1 break if activate_at is None: # Activate after the shebang. activate_at = 1 return lines[:activate_at] + ['', activate, ''] + lines[activate_at:]
[ "def", "relative_script", "(", "lines", ")", ":", "activate", "=", "\"import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this\"", "# Find the last future statement in the script. If we insert the activation", "# line before a future statement, Python will raise a SyntaxError.", "activate_at", "=", "None", "for", "idx", ",", "line", "in", "reversed", "(", "list", "(", "enumerate", "(", "lines", ")", ")", ")", ":", "if", "line", ".", "split", "(", ")", "[", ":", "3", "]", "==", "[", "'from'", ",", "'__future__'", ",", "'import'", "]", ":", "activate_at", "=", "idx", "+", "1", "break", "if", "activate_at", "is", "None", ":", "# Activate after the shebang.", "activate_at", "=", "1", "return", "lines", "[", ":", "activate_at", "]", "+", "[", "''", ",", "activate", ",", "''", "]", "+", "lines", "[", "activate_at", ":", "]" ]
Return a script that'll work in a relocatable environment.
[ "Return", "a", "script", "that", "ll", "work", "in", "a", "relocatable", "environment", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L1670-L1683
232,677
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
fixup_pth_and_egg_link
def fixup_pth_and_egg_link(home_dir, sys_path=None): """Makes .pth and .egg-link files use relative paths""" home_dir = os.path.normcase(os.path.abspath(home_dir)) if sys_path is None: sys_path = sys.path for path in sys_path: if not path: path = '.' if not os.path.isdir(path): continue path = os.path.normcase(os.path.abspath(path)) if not path.startswith(home_dir): logger.debug('Skipping system (non-environment) directory %s' % path) continue for filename in os.listdir(path): filename = os.path.join(path, filename) if filename.endswith('.pth'): if not os.access(filename, os.W_OK): logger.warn('Cannot write .pth file %s, skipping' % filename) else: fixup_pth_file(filename) if filename.endswith('.egg-link'): if not os.access(filename, os.W_OK): logger.warn('Cannot write .egg-link file %s, skipping' % filename) else: fixup_egg_link(filename)
python
def fixup_pth_and_egg_link(home_dir, sys_path=None): """Makes .pth and .egg-link files use relative paths""" home_dir = os.path.normcase(os.path.abspath(home_dir)) if sys_path is None: sys_path = sys.path for path in sys_path: if not path: path = '.' if not os.path.isdir(path): continue path = os.path.normcase(os.path.abspath(path)) if not path.startswith(home_dir): logger.debug('Skipping system (non-environment) directory %s' % path) continue for filename in os.listdir(path): filename = os.path.join(path, filename) if filename.endswith('.pth'): if not os.access(filename, os.W_OK): logger.warn('Cannot write .pth file %s, skipping' % filename) else: fixup_pth_file(filename) if filename.endswith('.egg-link'): if not os.access(filename, os.W_OK): logger.warn('Cannot write .egg-link file %s, skipping' % filename) else: fixup_egg_link(filename)
[ "def", "fixup_pth_and_egg_link", "(", "home_dir", ",", "sys_path", "=", "None", ")", ":", "home_dir", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "home_dir", ")", ")", "if", "sys_path", "is", "None", ":", "sys_path", "=", "sys", ".", "path", "for", "path", "in", "sys_path", ":", "if", "not", "path", ":", "path", "=", "'.'", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "continue", "path", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "if", "not", "path", ".", "startswith", "(", "home_dir", ")", ":", "logger", ".", "debug", "(", "'Skipping system (non-environment) directory %s'", "%", "path", ")", "continue", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "if", "filename", ".", "endswith", "(", "'.pth'", ")", ":", "if", "not", "os", ".", "access", "(", "filename", ",", "os", ".", "W_OK", ")", ":", "logger", ".", "warn", "(", "'Cannot write .pth file %s, skipping'", "%", "filename", ")", "else", ":", "fixup_pth_file", "(", "filename", ")", "if", "filename", ".", "endswith", "(", "'.egg-link'", ")", ":", "if", "not", "os", ".", "access", "(", "filename", ",", "os", ".", "W_OK", ")", ":", "logger", ".", "warn", "(", "'Cannot write .egg-link file %s, skipping'", "%", "filename", ")", "else", ":", "fixup_egg_link", "(", "filename", ")" ]
Makes .pth and .egg-link files use relative paths
[ "Makes", ".", "pth", "and", ".", "egg", "-", "link", "files", "use", "relative", "paths" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L1685-L1710
232,678
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
make_relative_path
def make_relative_path(source, dest, dest_is_directory=True): """ Make a filename relative, where the filename is dest, and it is being referred to from the filename source. >>> make_relative_path('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../another-place/src/Directory' >>> make_relative_path('/usr/share/something/a-file.pth', ... '/home/user/src/Directory') '../../../home/user/src/Directory' >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/') './' """ source = os.path.dirname(source) if not dest_is_directory: dest_filename = os.path.basename(dest) dest = os.path.dirname(dest) dest = os.path.normpath(os.path.abspath(dest)) source = os.path.normpath(os.path.abspath(source)) dest_parts = dest.strip(os.path.sep).split(os.path.sep) source_parts = source.strip(os.path.sep).split(os.path.sep) while dest_parts and source_parts and dest_parts[0] == source_parts[0]: dest_parts.pop(0) source_parts.pop(0) full_parts = ['..']*len(source_parts) + dest_parts if not dest_is_directory: full_parts.append(dest_filename) if not full_parts: # Special case for the current directory (otherwise it'd be '') return './' return os.path.sep.join(full_parts)
python
def make_relative_path(source, dest, dest_is_directory=True): """ Make a filename relative, where the filename is dest, and it is being referred to from the filename source. >>> make_relative_path('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../another-place/src/Directory' >>> make_relative_path('/usr/share/something/a-file.pth', ... '/home/user/src/Directory') '../../../home/user/src/Directory' >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/') './' """ source = os.path.dirname(source) if not dest_is_directory: dest_filename = os.path.basename(dest) dest = os.path.dirname(dest) dest = os.path.normpath(os.path.abspath(dest)) source = os.path.normpath(os.path.abspath(source)) dest_parts = dest.strip(os.path.sep).split(os.path.sep) source_parts = source.strip(os.path.sep).split(os.path.sep) while dest_parts and source_parts and dest_parts[0] == source_parts[0]: dest_parts.pop(0) source_parts.pop(0) full_parts = ['..']*len(source_parts) + dest_parts if not dest_is_directory: full_parts.append(dest_filename) if not full_parts: # Special case for the current directory (otherwise it'd be '') return './' return os.path.sep.join(full_parts)
[ "def", "make_relative_path", "(", "source", ",", "dest", ",", "dest_is_directory", "=", "True", ")", ":", "source", "=", "os", ".", "path", ".", "dirname", "(", "source", ")", "if", "not", "dest_is_directory", ":", "dest_filename", "=", "os", ".", "path", ".", "basename", "(", "dest", ")", "dest", "=", "os", ".", "path", ".", "dirname", "(", "dest", ")", "dest", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "dest", ")", ")", "source", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "source", ")", ")", "dest_parts", "=", "dest", ".", "strip", "(", "os", ".", "path", ".", "sep", ")", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "source_parts", "=", "source", ".", "strip", "(", "os", ".", "path", ".", "sep", ")", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "while", "dest_parts", "and", "source_parts", "and", "dest_parts", "[", "0", "]", "==", "source_parts", "[", "0", "]", ":", "dest_parts", ".", "pop", "(", "0", ")", "source_parts", ".", "pop", "(", "0", ")", "full_parts", "=", "[", "'..'", "]", "*", "len", "(", "source_parts", ")", "+", "dest_parts", "if", "not", "dest_is_directory", ":", "full_parts", ".", "append", "(", "dest_filename", ")", "if", "not", "full_parts", ":", "# Special case for the current directory (otherwise it'd be '')", "return", "'./'", "return", "os", ".", "path", ".", "sep", ".", "join", "(", "full_parts", ")" ]
Make a filename relative, where the filename is dest, and it is being referred to from the filename source. >>> make_relative_path('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../another-place/src/Directory' >>> make_relative_path('/usr/share/something/a-file.pth', ... '/home/user/src/Directory') '../../../home/user/src/Directory' >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/') './'
[ "Make", "a", "filename", "relative", "where", "the", "filename", "is", "dest", "and", "it", "is", "being", "referred", "to", "from", "the", "filename", "source", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L1749-L1780
232,679
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
create_bootstrap_script
def create_bootstrap_script(extra_text, python_version=''): """ Creates a bootstrap script, which is like this script but with extend_parser, adjust_options, and after_install hooks. This returns a string that (written to disk of course) can be used as a bootstrap script with your own customizations. The script will be the standard virtualenv.py script, with your extra text added (your extra text should be Python code). If you include these functions, they will be called: ``extend_parser(optparse_parser)``: You can add or remove options from the parser here. ``adjust_options(options, args)``: You can change options here, or change the args (if you accept different kinds of arguments, be sure you modify ``args`` so it is only ``[DEST_DIR]``). ``after_install(options, home_dir)``: After everything is installed, this function is called. This is probably the function you are most likely to use. An example would be:: def after_install(options, home_dir): subprocess.call([join(home_dir, 'bin', 'easy_install'), 'MyPackage']) subprocess.call([join(home_dir, 'bin', 'my-package-script'), 'setup', home_dir]) This example immediately installs a package, and runs a setup script from that package. If you provide something like ``python_version='2.5'`` then the script will start with ``#!/usr/bin/env python2.5`` instead of ``#!/usr/bin/env python``. You can use this when the script must be run with a particular Python version. """ filename = __file__ if filename.endswith('.pyc'): filename = filename[:-1] f = codecs.open(filename, 'r', encoding='utf-8') content = f.read() f.close() py_exe = 'python%s' % python_version content = (('#!/usr/bin/env %s\n' % py_exe) + '## WARNING: This file is generated\n' + content) return content.replace('##EXT' 'END##', extra_text)
python
def create_bootstrap_script(extra_text, python_version=''): """ Creates a bootstrap script, which is like this script but with extend_parser, adjust_options, and after_install hooks. This returns a string that (written to disk of course) can be used as a bootstrap script with your own customizations. The script will be the standard virtualenv.py script, with your extra text added (your extra text should be Python code). If you include these functions, they will be called: ``extend_parser(optparse_parser)``: You can add or remove options from the parser here. ``adjust_options(options, args)``: You can change options here, or change the args (if you accept different kinds of arguments, be sure you modify ``args`` so it is only ``[DEST_DIR]``). ``after_install(options, home_dir)``: After everything is installed, this function is called. This is probably the function you are most likely to use. An example would be:: def after_install(options, home_dir): subprocess.call([join(home_dir, 'bin', 'easy_install'), 'MyPackage']) subprocess.call([join(home_dir, 'bin', 'my-package-script'), 'setup', home_dir]) This example immediately installs a package, and runs a setup script from that package. If you provide something like ``python_version='2.5'`` then the script will start with ``#!/usr/bin/env python2.5`` instead of ``#!/usr/bin/env python``. You can use this when the script must be run with a particular Python version. """ filename = __file__ if filename.endswith('.pyc'): filename = filename[:-1] f = codecs.open(filename, 'r', encoding='utf-8') content = f.read() f.close() py_exe = 'python%s' % python_version content = (('#!/usr/bin/env %s\n' % py_exe) + '## WARNING: This file is generated\n' + content) return content.replace('##EXT' 'END##', extra_text)
[ "def", "create_bootstrap_script", "(", "extra_text", ",", "python_version", "=", "''", ")", ":", "filename", "=", "__file__", "if", "filename", ".", "endswith", "(", "'.pyc'", ")", ":", "filename", "=", "filename", "[", ":", "-", "1", "]", "f", "=", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "content", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "py_exe", "=", "'python%s'", "%", "python_version", "content", "=", "(", "(", "'#!/usr/bin/env %s\\n'", "%", "py_exe", ")", "+", "'## WARNING: This file is generated\\n'", "+", "content", ")", "return", "content", ".", "replace", "(", "'##EXT'", "'END##'", ",", "extra_text", ")" ]
Creates a bootstrap script, which is like this script but with extend_parser, adjust_options, and after_install hooks. This returns a string that (written to disk of course) can be used as a bootstrap script with your own customizations. The script will be the standard virtualenv.py script, with your extra text added (your extra text should be Python code). If you include these functions, they will be called: ``extend_parser(optparse_parser)``: You can add or remove options from the parser here. ``adjust_options(options, args)``: You can change options here, or change the args (if you accept different kinds of arguments, be sure you modify ``args`` so it is only ``[DEST_DIR]``). ``after_install(options, home_dir)``: After everything is installed, this function is called. This is probably the function you are most likely to use. An example would be:: def after_install(options, home_dir): subprocess.call([join(home_dir, 'bin', 'easy_install'), 'MyPackage']) subprocess.call([join(home_dir, 'bin', 'my-package-script'), 'setup', home_dir]) This example immediately installs a package, and runs a setup script from that package. If you provide something like ``python_version='2.5'`` then the script will start with ``#!/usr/bin/env python2.5`` instead of ``#!/usr/bin/env python``. You can use this when the script must be run with a particular Python version.
[ "Creates", "a", "bootstrap", "script", "which", "is", "like", "this", "script", "but", "with", "extend_parser", "adjust_options", "and", "after_install", "hooks", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L1787-L1837
232,680
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
read_data
def read_data(file, endian, num=1): """ Read a given number of 32-bits unsigned integers from the given file with the given endianness. """ res = struct.unpack(endian + 'L' * num, file.read(num * 4)) if len(res) == 1: return res[0] return res
python
def read_data(file, endian, num=1): """ Read a given number of 32-bits unsigned integers from the given file with the given endianness. """ res = struct.unpack(endian + 'L' * num, file.read(num * 4)) if len(res) == 1: return res[0] return res
[ "def", "read_data", "(", "file", ",", "endian", ",", "num", "=", "1", ")", ":", "res", "=", "struct", ".", "unpack", "(", "endian", "+", "'L'", "*", "num", ",", "file", ".", "read", "(", "num", "*", "4", ")", ")", "if", "len", "(", "res", ")", "==", "1", ":", "return", "res", "[", "0", "]", "return", "res" ]
Read a given number of 32-bits unsigned integers from the given file with the given endianness.
[ "Read", "a", "given", "number", "of", "32", "-", "bits", "unsigned", "integers", "from", "the", "given", "file", "with", "the", "given", "endianness", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L2269-L2277
232,681
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
Logger._stdout_level
def _stdout_level(self): """Returns the level that stdout runs at""" for level, consumer in self.consumers: if consumer is sys.stdout: return level return self.FATAL
python
def _stdout_level(self): """Returns the level that stdout runs at""" for level, consumer in self.consumers: if consumer is sys.stdout: return level return self.FATAL
[ "def", "_stdout_level", "(", "self", ")", ":", "for", "level", ",", "consumer", "in", "self", ".", "consumers", ":", "if", "consumer", "is", "sys", ".", "stdout", ":", "return", "level", "return", "self", ".", "FATAL" ]
Returns the level that stdout runs at
[ "Returns", "the", "level", "that", "stdout", "runs", "at" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L396-L401
232,682
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
ConfigOptionParser.get_config_section
def get_config_section(self, name): """ Get a section of a configuration """ if self.config.has_section(name): return self.config.items(name) return []
python
def get_config_section(self, name): """ Get a section of a configuration """ if self.config.has_section(name): return self.config.items(name) return []
[ "def", "get_config_section", "(", "self", ",", "name", ")", ":", "if", "self", ".", "config", ".", "has_section", "(", "name", ")", ":", "return", "self", ".", "config", ".", "items", "(", "name", ")", "return", "[", "]" ]
Get a section of a configuration
[ "Get", "a", "section", "of", "a", "configuration" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L610-L616
232,683
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
ConfigOptionParser.get_environ_vars
def get_environ_vars(self, prefix='VIRTUALENV_'): """ Returns a generator with all environmental vars with prefix VIRTUALENV """ for key, val in os.environ.items(): if key.startswith(prefix): yield (key.replace(prefix, '').lower(), val)
python
def get_environ_vars(self, prefix='VIRTUALENV_'): """ Returns a generator with all environmental vars with prefix VIRTUALENV """ for key, val in os.environ.items(): if key.startswith(prefix): yield (key.replace(prefix, '').lower(), val)
[ "def", "get_environ_vars", "(", "self", ",", "prefix", "=", "'VIRTUALENV_'", ")", ":", "for", "key", ",", "val", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "prefix", ")", ":", "yield", "(", "key", ".", "replace", "(", "prefix", ",", "''", ")", ".", "lower", "(", ")", ",", "val", ")" ]
Returns a generator with all environmental vars with prefix VIRTUALENV
[ "Returns", "a", "generator", "with", "all", "environmental", "vars", "with", "prefix", "VIRTUALENV" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L618-L624
232,684
nerdvegas/rez
src/rez/config.py
Config.copy
def copy(self, overrides=None, locked=False): """Create a separate copy of this config.""" other = copy.copy(self) if overrides is not None: other.overrides = overrides other.locked = locked other._uncache() return other
python
def copy(self, overrides=None, locked=False): """Create a separate copy of this config.""" other = copy.copy(self) if overrides is not None: other.overrides = overrides other.locked = locked other._uncache() return other
[ "def", "copy", "(", "self", ",", "overrides", "=", "None", ",", "locked", "=", "False", ")", ":", "other", "=", "copy", ".", "copy", "(", "self", ")", "if", "overrides", "is", "not", "None", ":", "other", ".", "overrides", "=", "overrides", "other", ".", "locked", "=", "locked", "other", ".", "_uncache", "(", ")", "return", "other" ]
Create a separate copy of this config.
[ "Create", "a", "separate", "copy", "of", "this", "config", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L429-L439
232,685
nerdvegas/rez
src/rez/config.py
Config.override
def override(self, key, value): """Set a setting to the given value. Note that `key` can be in dotted form, eg 'plugins.release_hook.emailer.sender'. """ keys = key.split('.') if len(keys) > 1: if keys[0] != "plugins": raise AttributeError("no such setting: %r" % key) self.plugins.override(keys[1:], value) else: self.overrides[key] = value self._uncache(key)
python
def override(self, key, value): """Set a setting to the given value. Note that `key` can be in dotted form, eg 'plugins.release_hook.emailer.sender'. """ keys = key.split('.') if len(keys) > 1: if keys[0] != "plugins": raise AttributeError("no such setting: %r" % key) self.plugins.override(keys[1:], value) else: self.overrides[key] = value self._uncache(key)
[ "def", "override", "(", "self", ",", "key", ",", "value", ")", ":", "keys", "=", "key", ".", "split", "(", "'.'", ")", "if", "len", "(", "keys", ")", ">", "1", ":", "if", "keys", "[", "0", "]", "!=", "\"plugins\"", ":", "raise", "AttributeError", "(", "\"no such setting: %r\"", "%", "key", ")", "self", ".", "plugins", ".", "override", "(", "keys", "[", "1", ":", "]", ",", "value", ")", "else", ":", "self", ".", "overrides", "[", "key", "]", "=", "value", "self", ".", "_uncache", "(", "key", ")" ]
Set a setting to the given value. Note that `key` can be in dotted form, eg 'plugins.release_hook.emailer.sender'.
[ "Set", "a", "setting", "to", "the", "given", "value", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L441-L454
232,686
nerdvegas/rez
src/rez/config.py
Config.remove_override
def remove_override(self, key): """Remove a setting override, if one exists.""" keys = key.split('.') if len(keys) > 1: raise NotImplementedError elif key in self.overrides: del self.overrides[key] self._uncache(key)
python
def remove_override(self, key): """Remove a setting override, if one exists.""" keys = key.split('.') if len(keys) > 1: raise NotImplementedError elif key in self.overrides: del self.overrides[key] self._uncache(key)
[ "def", "remove_override", "(", "self", ",", "key", ")", ":", "keys", "=", "key", ".", "split", "(", "'.'", ")", "if", "len", "(", "keys", ")", ">", "1", ":", "raise", "NotImplementedError", "elif", "key", "in", "self", ".", "overrides", ":", "del", "self", ".", "overrides", "[", "key", "]", "self", ".", "_uncache", "(", "key", ")" ]
Remove a setting override, if one exists.
[ "Remove", "a", "setting", "override", "if", "one", "exists", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L459-L466
232,687
nerdvegas/rez
src/rez/config.py
Config.warn
def warn(self, key): """Returns True if the warning setting is enabled.""" return (not self.quiet and not self.warn_none and (self.warn_all or getattr(self, "warn_%s" % key)))
python
def warn(self, key): """Returns True if the warning setting is enabled.""" return (not self.quiet and not self.warn_none and (self.warn_all or getattr(self, "warn_%s" % key)))
[ "def", "warn", "(", "self", ",", "key", ")", ":", "return", "(", "not", "self", ".", "quiet", "and", "not", "self", ".", "warn_none", "and", "(", "self", ".", "warn_all", "or", "getattr", "(", "self", ",", "\"warn_%s\"", "%", "key", ")", ")", ")" ]
Returns True if the warning setting is enabled.
[ "Returns", "True", "if", "the", "warning", "setting", "is", "enabled", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L468-L471
232,688
nerdvegas/rez
src/rez/config.py
Config.debug
def debug(self, key): """Returns True if the debug setting is enabled.""" return (not self.quiet and not self.debug_none and (self.debug_all or getattr(self, "debug_%s" % key)))
python
def debug(self, key): """Returns True if the debug setting is enabled.""" return (not self.quiet and not self.debug_none and (self.debug_all or getattr(self, "debug_%s" % key)))
[ "def", "debug", "(", "self", ",", "key", ")", ":", "return", "(", "not", "self", ".", "quiet", "and", "not", "self", ".", "debug_none", "and", "(", "self", ".", "debug_all", "or", "getattr", "(", "self", ",", "\"debug_%s\"", "%", "key", ")", ")", ")" ]
Returns True if the debug setting is enabled.
[ "Returns", "True", "if", "the", "debug", "setting", "is", "enabled", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L473-L476
232,689
nerdvegas/rez
src/rez/config.py
Config.data
def data(self): """Returns the entire configuration as a dict. Note that this will force all plugins to be loaded. """ d = {} for key in self._data: if key == "plugins": d[key] = self.plugins.data() else: try: d[key] = getattr(self, key) except AttributeError: pass # unknown key, just leave it unchanged return d
python
def data(self): """Returns the entire configuration as a dict. Note that this will force all plugins to be loaded. """ d = {} for key in self._data: if key == "plugins": d[key] = self.plugins.data() else: try: d[key] = getattr(self, key) except AttributeError: pass # unknown key, just leave it unchanged return d
[ "def", "data", "(", "self", ")", ":", "d", "=", "{", "}", "for", "key", "in", "self", ".", "_data", ":", "if", "key", "==", "\"plugins\"", ":", "d", "[", "key", "]", "=", "self", ".", "plugins", ".", "data", "(", ")", "else", ":", "try", ":", "d", "[", "key", "]", "=", "getattr", "(", "self", ",", "key", ")", "except", "AttributeError", ":", "pass", "# unknown key, just leave it unchanged", "return", "d" ]
Returns the entire configuration as a dict. Note that this will force all plugins to be loaded.
[ "Returns", "the", "entire", "configuration", "as", "a", "dict", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L507-L521
232,690
nerdvegas/rez
src/rez/config.py
Config.nonlocal_packages_path
def nonlocal_packages_path(self): """Returns package search paths with local path removed.""" paths = self.packages_path[:] if self.local_packages_path in paths: paths.remove(self.local_packages_path) return paths
python
def nonlocal_packages_path(self): """Returns package search paths with local path removed.""" paths = self.packages_path[:] if self.local_packages_path in paths: paths.remove(self.local_packages_path) return paths
[ "def", "nonlocal_packages_path", "(", "self", ")", ":", "paths", "=", "self", ".", "packages_path", "[", ":", "]", "if", "self", ".", "local_packages_path", "in", "paths", ":", "paths", ".", "remove", "(", "self", ".", "local_packages_path", ")", "return", "paths" ]
Returns package search paths with local path removed.
[ "Returns", "package", "search", "paths", "with", "local", "path", "removed", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L524-L529
232,691
nerdvegas/rez
src/rez/config.py
Config._swap
def _swap(self, other): """Swap this config with another. This is used by the unit tests to swap the config to one that is shielded from any user config updates. Do not use this method unless you have good reason. """ self.__dict__, other.__dict__ = other.__dict__, self.__dict__
python
def _swap(self, other): """Swap this config with another. This is used by the unit tests to swap the config to one that is shielded from any user config updates. Do not use this method unless you have good reason. """ self.__dict__, other.__dict__ = other.__dict__, self.__dict__
[ "def", "_swap", "(", "self", ",", "other", ")", ":", "self", ".", "__dict__", ",", "other", ".", "__dict__", "=", "other", ".", "__dict__", ",", "self", ".", "__dict__" ]
Swap this config with another. This is used by the unit tests to swap the config to one that is shielded from any user config updates. Do not use this method unless you have good reason.
[ "Swap", "this", "config", "with", "another", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L568-L575
232,692
nerdvegas/rez
src/rez/config.py
Config._create_main_config
def _create_main_config(cls, overrides=None): """See comment block at top of 'rezconfig' describing how the main config is assembled.""" filepaths = [] filepaths.append(get_module_root_config()) filepath = os.getenv("REZ_CONFIG_FILE") if filepath: filepaths.extend(filepath.split(os.pathsep)) filepath = os.path.expanduser("~/.rezconfig") filepaths.append(filepath) return Config(filepaths, overrides)
python
def _create_main_config(cls, overrides=None): """See comment block at top of 'rezconfig' describing how the main config is assembled.""" filepaths = [] filepaths.append(get_module_root_config()) filepath = os.getenv("REZ_CONFIG_FILE") if filepath: filepaths.extend(filepath.split(os.pathsep)) filepath = os.path.expanduser("~/.rezconfig") filepaths.append(filepath) return Config(filepaths, overrides)
[ "def", "_create_main_config", "(", "cls", ",", "overrides", "=", "None", ")", ":", "filepaths", "=", "[", "]", "filepaths", ".", "append", "(", "get_module_root_config", "(", ")", ")", "filepath", "=", "os", ".", "getenv", "(", "\"REZ_CONFIG_FILE\"", ")", "if", "filepath", ":", "filepaths", ".", "extend", "(", "filepath", ".", "split", "(", "os", ".", "pathsep", ")", ")", "filepath", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.rezconfig\"", ")", "filepaths", ".", "append", "(", "filepath", ")", "return", "Config", "(", "filepaths", ",", "overrides", ")" ]
See comment block at top of 'rezconfig' describing how the main config is assembled.
[ "See", "comment", "block", "at", "top", "of", "rezconfig", "describing", "how", "the", "main", "config", "is", "assembled", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L600-L612
232,693
nerdvegas/rez
src/rez/utils/platform_mapped.py
platform_mapped
def platform_mapped(func): """Decorates functions for lookups within a config.platform_map dictionary. The first level key is mapped to the func.__name__ of the decorated function. Regular expressions are used on the second level key, values. Note that there is no guaranteed order within the dictionary evaluation. Only the first matching regular expression is being used. For example: config.platform_map = { "os": { r"Scientific Linux-(.*)": r"Scientific-\1", # Scientific Linux-x.x -> Scientific-x.x r"Ubuntu-14.\d": r"Ubuntu-14", # Any Ubuntu-14.x -> Ubuntu-14 }, "arch": { "x86_64": "64bit", # Maps both x86_64 and amd64 -> 64bit (don't) "amd64": "64bit", }, } """ def inner(*args, **kwargs): # Since platform is being used within config lazy import config to prevent # circular dependencies from rez.config import config # Original result result = func(*args, **kwargs) # The function name is used as primary key entry = config.platform_map.get(func.__name__) if entry: for key, value in entry.iteritems(): result, changes = re.subn(key, value, result) if changes > 0: break return result return inner
python
def platform_mapped(func): """Decorates functions for lookups within a config.platform_map dictionary. The first level key is mapped to the func.__name__ of the decorated function. Regular expressions are used on the second level key, values. Note that there is no guaranteed order within the dictionary evaluation. Only the first matching regular expression is being used. For example: config.platform_map = { "os": { r"Scientific Linux-(.*)": r"Scientific-\1", # Scientific Linux-x.x -> Scientific-x.x r"Ubuntu-14.\d": r"Ubuntu-14", # Any Ubuntu-14.x -> Ubuntu-14 }, "arch": { "x86_64": "64bit", # Maps both x86_64 and amd64 -> 64bit (don't) "amd64": "64bit", }, } """ def inner(*args, **kwargs): # Since platform is being used within config lazy import config to prevent # circular dependencies from rez.config import config # Original result result = func(*args, **kwargs) # The function name is used as primary key entry = config.platform_map.get(func.__name__) if entry: for key, value in entry.iteritems(): result, changes = re.subn(key, value, result) if changes > 0: break return result return inner
[ "def", "platform_mapped", "(", "func", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Since platform is being used within config lazy import config to prevent", "# circular dependencies", "from", "rez", ".", "config", "import", "config", "# Original result", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# The function name is used as primary key", "entry", "=", "config", ".", "platform_map", ".", "get", "(", "func", ".", "__name__", ")", "if", "entry", ":", "for", "key", ",", "value", "in", "entry", ".", "iteritems", "(", ")", ":", "result", ",", "changes", "=", "re", ".", "subn", "(", "key", ",", "value", ",", "result", ")", "if", "changes", ">", "0", ":", "break", "return", "result", "return", "inner" ]
Decorates functions for lookups within a config.platform_map dictionary. The first level key is mapped to the func.__name__ of the decorated function. Regular expressions are used on the second level key, values. Note that there is no guaranteed order within the dictionary evaluation. Only the first matching regular expression is being used. For example: config.platform_map = { "os": { r"Scientific Linux-(.*)": r"Scientific-\1", # Scientific Linux-x.x -> Scientific-x.x r"Ubuntu-14.\d": r"Ubuntu-14", # Any Ubuntu-14.x -> Ubuntu-14 }, "arch": { "x86_64": "64bit", # Maps both x86_64 and amd64 -> 64bit (don't) "amd64": "64bit", }, }
[ "Decorates", "functions", "for", "lookups", "within", "a", "config", ".", "platform_map", "dictionary", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/platform_mapped.py#L4-L42
232,694
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/pagerank.py
pagerank
def pagerank(graph, damping_factor=0.85, max_iterations=100, min_delta=0.00001): """ Compute and return the PageRank in an directed graph. @type graph: digraph @param graph: Digraph. @type damping_factor: number @param damping_factor: PageRank dumping factor. @type max_iterations: number @param max_iterations: Maximum number of iterations. @type min_delta: number @param min_delta: Smallest variation required to have a new iteration. @rtype: Dict @return: Dict containing all the nodes PageRank. """ nodes = graph.nodes() graph_size = len(nodes) if graph_size == 0: return {} min_value = (1.0-damping_factor)/graph_size #value for nodes without inbound links # itialize the page rank dict with 1/N for all nodes pagerank = dict.fromkeys(nodes, 1.0/graph_size) for i in range(max_iterations): diff = 0 #total difference compared to last iteraction # computes each node PageRank based on inbound links for node in nodes: rank = min_value for referring_page in graph.incidents(node): rank += damping_factor * pagerank[referring_page] / len(graph.neighbors(referring_page)) diff += abs(pagerank[node] - rank) pagerank[node] = rank #stop if PageRank has converged if diff < min_delta: break return pagerank
python
def pagerank(graph, damping_factor=0.85, max_iterations=100, min_delta=0.00001): """ Compute and return the PageRank in an directed graph. @type graph: digraph @param graph: Digraph. @type damping_factor: number @param damping_factor: PageRank dumping factor. @type max_iterations: number @param max_iterations: Maximum number of iterations. @type min_delta: number @param min_delta: Smallest variation required to have a new iteration. @rtype: Dict @return: Dict containing all the nodes PageRank. """ nodes = graph.nodes() graph_size = len(nodes) if graph_size == 0: return {} min_value = (1.0-damping_factor)/graph_size #value for nodes without inbound links # itialize the page rank dict with 1/N for all nodes pagerank = dict.fromkeys(nodes, 1.0/graph_size) for i in range(max_iterations): diff = 0 #total difference compared to last iteraction # computes each node PageRank based on inbound links for node in nodes: rank = min_value for referring_page in graph.incidents(node): rank += damping_factor * pagerank[referring_page] / len(graph.neighbors(referring_page)) diff += abs(pagerank[node] - rank) pagerank[node] = rank #stop if PageRank has converged if diff < min_delta: break return pagerank
[ "def", "pagerank", "(", "graph", ",", "damping_factor", "=", "0.85", ",", "max_iterations", "=", "100", ",", "min_delta", "=", "0.00001", ")", ":", "nodes", "=", "graph", ".", "nodes", "(", ")", "graph_size", "=", "len", "(", "nodes", ")", "if", "graph_size", "==", "0", ":", "return", "{", "}", "min_value", "=", "(", "1.0", "-", "damping_factor", ")", "/", "graph_size", "#value for nodes without inbound links", "# itialize the page rank dict with 1/N for all nodes", "pagerank", "=", "dict", ".", "fromkeys", "(", "nodes", ",", "1.0", "/", "graph_size", ")", "for", "i", "in", "range", "(", "max_iterations", ")", ":", "diff", "=", "0", "#total difference compared to last iteraction", "# computes each node PageRank based on inbound links", "for", "node", "in", "nodes", ":", "rank", "=", "min_value", "for", "referring_page", "in", "graph", ".", "incidents", "(", "node", ")", ":", "rank", "+=", "damping_factor", "*", "pagerank", "[", "referring_page", "]", "/", "len", "(", "graph", ".", "neighbors", "(", "referring_page", ")", ")", "diff", "+=", "abs", "(", "pagerank", "[", "node", "]", "-", "rank", ")", "pagerank", "[", "node", "]", "=", "rank", "#stop if PageRank has converged", "if", "diff", "<", "min_delta", ":", "break", "return", "pagerank" ]
Compute and return the PageRank in an directed graph. @type graph: digraph @param graph: Digraph. @type damping_factor: number @param damping_factor: PageRank dumping factor. @type max_iterations: number @param max_iterations: Maximum number of iterations. @type min_delta: number @param min_delta: Smallest variation required to have a new iteration. @rtype: Dict @return: Dict containing all the nodes PageRank.
[ "Compute", "and", "return", "the", "PageRank", "in", "an", "directed", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/pagerank.py#L32-L76
232,695
nerdvegas/rez
src/rez/package_py_utils.py
exec_command
def exec_command(attr, cmd): """Runs a subproc to calculate a package attribute. """ import subprocess p = popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: from rez.exceptions import InvalidPackageError raise InvalidPackageError( "Error determining package attribute '%s':\n%s" % (attr, err)) return out.strip(), err.strip()
python
def exec_command(attr, cmd): """Runs a subproc to calculate a package attribute. """ import subprocess p = popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: from rez.exceptions import InvalidPackageError raise InvalidPackageError( "Error determining package attribute '%s':\n%s" % (attr, err)) return out.strip(), err.strip()
[ "def", "exec_command", "(", "attr", ",", "cmd", ")", ":", "import", "subprocess", "p", "=", "popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "from", "rez", ".", "exceptions", "import", "InvalidPackageError", "raise", "InvalidPackageError", "(", "\"Error determining package attribute '%s':\\n%s\"", "%", "(", "attr", ",", "err", ")", ")", "return", "out", ".", "strip", "(", ")", ",", "err", ".", "strip", "(", ")" ]
Runs a subproc to calculate a package attribute.
[ "Runs", "a", "subproc", "to", "calculate", "a", "package", "attribute", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_py_utils.py#L163-L176
232,696
nerdvegas/rez
src/rez/package_py_utils.py
exec_python
def exec_python(attr, src, executable="python"): """Runs a python subproc to calculate a package attribute. Args: attr (str): Name of package attribute being created. src (list of str): Python code to execute, will be converted into semicolon-delimited single line of code. Returns: str: Output of python process. """ import subprocess if isinstance(src, basestring): src = [src] p = popen([executable, "-c", "; ".join(src)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: from rez.exceptions import InvalidPackageError raise InvalidPackageError( "Error determining package attribute '%s':\n%s" % (attr, err)) return out.strip()
python
def exec_python(attr, src, executable="python"): """Runs a python subproc to calculate a package attribute. Args: attr (str): Name of package attribute being created. src (list of str): Python code to execute, will be converted into semicolon-delimited single line of code. Returns: str: Output of python process. """ import subprocess if isinstance(src, basestring): src = [src] p = popen([executable, "-c", "; ".join(src)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: from rez.exceptions import InvalidPackageError raise InvalidPackageError( "Error determining package attribute '%s':\n%s" % (attr, err)) return out.strip()
[ "def", "exec_python", "(", "attr", ",", "src", ",", "executable", "=", "\"python\"", ")", ":", "import", "subprocess", "if", "isinstance", "(", "src", ",", "basestring", ")", ":", "src", "=", "[", "src", "]", "p", "=", "popen", "(", "[", "executable", ",", "\"-c\"", ",", "\"; \"", ".", "join", "(", "src", ")", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "from", "rez", ".", "exceptions", "import", "InvalidPackageError", "raise", "InvalidPackageError", "(", "\"Error determining package attribute '%s':\\n%s\"", "%", "(", "attr", ",", "err", ")", ")", "return", "out", ".", "strip", "(", ")" ]
Runs a python subproc to calculate a package attribute. Args: attr (str): Name of package attribute being created. src (list of str): Python code to execute, will be converted into semicolon-delimited single line of code. Returns: str: Output of python process.
[ "Runs", "a", "python", "subproc", "to", "calculate", "a", "package", "attribute", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_py_utils.py#L179-L204
232,697
nerdvegas/rez
src/rez/package_py_utils.py
find_site_python
def find_site_python(module_name, paths=None): """Find the rez native python package that contains the given module. This function is used by python 'native' rez installers to find the native rez python package that represents the python installation that this module is installed into. Note: This function is dependent on the behavior found in the python '_native' package found in the 'rez-recipes' repository. Specifically, it expects to find a python package with a '_site_paths' list attribute listing the site directories associated with the python installation. Args: module_name (str): Target python module. paths (list of str, optional): paths to search for packages, defaults to `config.packages_path`. Returns: `Package`: Native python package containing the named module. """ from rez.packages_ import iter_packages import subprocess import ast import os py_cmd = 'import {x}; print {x}.__path__'.format(x=module_name) p = popen(["python", "-c", py_cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: raise InvalidPackageError( "Failed to find installed python module '%s':\n%s" % (module_name, err)) module_paths = ast.literal_eval(out.strip()) def issubdir(path, parent_path): return path.startswith(parent_path + os.sep) for package in iter_packages("python", paths=paths): if not hasattr(package, "_site_paths"): continue contained = True for module_path in module_paths: if not any(issubdir(module_path, x) for x in package._site_paths): contained = False if contained: return package raise InvalidPackageError( "Failed to find python installation containing the module '%s'. Has " "python been installed as a rez package?" % module_name)
python
def find_site_python(module_name, paths=None): """Find the rez native python package that contains the given module. This function is used by python 'native' rez installers to find the native rez python package that represents the python installation that this module is installed into. Note: This function is dependent on the behavior found in the python '_native' package found in the 'rez-recipes' repository. Specifically, it expects to find a python package with a '_site_paths' list attribute listing the site directories associated with the python installation. Args: module_name (str): Target python module. paths (list of str, optional): paths to search for packages, defaults to `config.packages_path`. Returns: `Package`: Native python package containing the named module. """ from rez.packages_ import iter_packages import subprocess import ast import os py_cmd = 'import {x}; print {x}.__path__'.format(x=module_name) p = popen(["python", "-c", py_cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: raise InvalidPackageError( "Failed to find installed python module '%s':\n%s" % (module_name, err)) module_paths = ast.literal_eval(out.strip()) def issubdir(path, parent_path): return path.startswith(parent_path + os.sep) for package in iter_packages("python", paths=paths): if not hasattr(package, "_site_paths"): continue contained = True for module_path in module_paths: if not any(issubdir(module_path, x) for x in package._site_paths): contained = False if contained: return package raise InvalidPackageError( "Failed to find python installation containing the module '%s'. Has " "python been installed as a rez package?" % module_name)
[ "def", "find_site_python", "(", "module_name", ",", "paths", "=", "None", ")", ":", "from", "rez", ".", "packages_", "import", "iter_packages", "import", "subprocess", "import", "ast", "import", "os", "py_cmd", "=", "'import {x}; print {x}.__path__'", ".", "format", "(", "x", "=", "module_name", ")", "p", "=", "popen", "(", "[", "\"python\"", ",", "\"-c\"", ",", "py_cmd", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "raise", "InvalidPackageError", "(", "\"Failed to find installed python module '%s':\\n%s\"", "%", "(", "module_name", ",", "err", ")", ")", "module_paths", "=", "ast", ".", "literal_eval", "(", "out", ".", "strip", "(", ")", ")", "def", "issubdir", "(", "path", ",", "parent_path", ")", ":", "return", "path", ".", "startswith", "(", "parent_path", "+", "os", ".", "sep", ")", "for", "package", "in", "iter_packages", "(", "\"python\"", ",", "paths", "=", "paths", ")", ":", "if", "not", "hasattr", "(", "package", ",", "\"_site_paths\"", ")", ":", "continue", "contained", "=", "True", "for", "module_path", "in", "module_paths", ":", "if", "not", "any", "(", "issubdir", "(", "module_path", ",", "x", ")", "for", "x", "in", "package", ".", "_site_paths", ")", ":", "contained", "=", "False", "if", "contained", ":", "return", "package", "raise", "InvalidPackageError", "(", "\"Failed to find python installation containing the module '%s'. Has \"", "\"python been installed as a rez package?\"", "%", "module_name", ")" ]
Find the rez native python package that contains the given module. This function is used by python 'native' rez installers to find the native rez python package that represents the python installation that this module is installed into. Note: This function is dependent on the behavior found in the python '_native' package found in the 'rez-recipes' repository. Specifically, it expects to find a python package with a '_site_paths' list attribute listing the site directories associated with the python installation. Args: module_name (str): Target python module. paths (list of str, optional): paths to search for packages, defaults to `config.packages_path`. Returns: `Package`: Native python package containing the named module.
[ "Find", "the", "rez", "native", "python", "package", "that", "contains", "the", "given", "module", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_py_utils.py#L207-L264
232,698
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/critical.py
_intersection
def _intersection(A,B): """ A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections """ intersection = [] for i in A: if i in B: intersection.append(i) return intersection
python
def _intersection(A,B): """ A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections """ intersection = [] for i in A: if i in B: intersection.append(i) return intersection
[ "def", "_intersection", "(", "A", ",", "B", ")", ":", "intersection", "=", "[", "]", "for", "i", "in", "A", ":", "if", "i", "in", "B", ":", "intersection", ".", "append", "(", "i", ")", "return", "intersection" ]
A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections
[ "A", "simple", "function", "to", "find", "an", "intersection", "between", "two", "arrays", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/critical.py#L38-L55
232,699
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/critical.py
critical_path
def critical_path(graph): """ Compute and return the critical path in an acyclic directed weighted graph. @attention: This function is only meaningful for directed weighted acyclic graphs @type graph: digraph @param graph: Digraph @rtype: List @return: List containing all the nodes in the path (or an empty array if the graph contains a cycle) """ #if the graph contains a cycle we return an empty array if not len(find_cycle(graph)) == 0: return [] #this empty dictionary will contain a tuple for every single node #the tuple contains the information about the most costly predecessor #of the given node and the cost of the path to this node #(predecessor, cost) node_tuples = {} topological_nodes = topological_sorting(graph) #all the tuples must be set to a default value for every node in the graph for node in topological_nodes: node_tuples.update( {node :(None, 0)} ) #run trough all the nodes in a topological order for node in topological_nodes: predecessors =[] #we must check all the predecessors for pre in graph.incidents(node): max_pre = node_tuples[pre][1] predecessors.append( (pre, graph.edge_weight( (pre, node) ) + max_pre ) ) max = 0; max_tuple = (None, 0) for i in predecessors:#look for the most costly predecessor if i[1] >= max: max = i[1] max_tuple = i #assign the maximum value to the given node in the node_tuples dictionary node_tuples[node] = max_tuple #find the critical node max = 0; critical_node = None for k,v in list(node_tuples.items()): if v[1] >= max: max= v[1] critical_node = k path = [] #find the critical path with backtracking trought the dictionary def mid_critical_path(end): if node_tuples[end][0] != None: path.append(end) mid_critical_path(node_tuples[end][0]) else: path.append(end) #call the recursive function mid_critical_path(critical_node) path.reverse() return path
python
def critical_path(graph): """ Compute and return the critical path in an acyclic directed weighted graph. @attention: This function is only meaningful for directed weighted acyclic graphs @type graph: digraph @param graph: Digraph @rtype: List @return: List containing all the nodes in the path (or an empty array if the graph contains a cycle) """ #if the graph contains a cycle we return an empty array if not len(find_cycle(graph)) == 0: return [] #this empty dictionary will contain a tuple for every single node #the tuple contains the information about the most costly predecessor #of the given node and the cost of the path to this node #(predecessor, cost) node_tuples = {} topological_nodes = topological_sorting(graph) #all the tuples must be set to a default value for every node in the graph for node in topological_nodes: node_tuples.update( {node :(None, 0)} ) #run trough all the nodes in a topological order for node in topological_nodes: predecessors =[] #we must check all the predecessors for pre in graph.incidents(node): max_pre = node_tuples[pre][1] predecessors.append( (pre, graph.edge_weight( (pre, node) ) + max_pre ) ) max = 0; max_tuple = (None, 0) for i in predecessors:#look for the most costly predecessor if i[1] >= max: max = i[1] max_tuple = i #assign the maximum value to the given node in the node_tuples dictionary node_tuples[node] = max_tuple #find the critical node max = 0; critical_node = None for k,v in list(node_tuples.items()): if v[1] >= max: max= v[1] critical_node = k path = [] #find the critical path with backtracking trought the dictionary def mid_critical_path(end): if node_tuples[end][0] != None: path.append(end) mid_critical_path(node_tuples[end][0]) else: path.append(end) #call the recursive function mid_critical_path(critical_node) path.reverse() return path
[ "def", "critical_path", "(", "graph", ")", ":", "#if the graph contains a cycle we return an empty array", "if", "not", "len", "(", "find_cycle", "(", "graph", ")", ")", "==", "0", ":", "return", "[", "]", "#this empty dictionary will contain a tuple for every single node", "#the tuple contains the information about the most costly predecessor ", "#of the given node and the cost of the path to this node", "#(predecessor, cost)", "node_tuples", "=", "{", "}", "topological_nodes", "=", "topological_sorting", "(", "graph", ")", "#all the tuples must be set to a default value for every node in the graph", "for", "node", "in", "topological_nodes", ":", "node_tuples", ".", "update", "(", "{", "node", ":", "(", "None", ",", "0", ")", "}", ")", "#run trough all the nodes in a topological order", "for", "node", "in", "topological_nodes", ":", "predecessors", "=", "[", "]", "#we must check all the predecessors", "for", "pre", "in", "graph", ".", "incidents", "(", "node", ")", ":", "max_pre", "=", "node_tuples", "[", "pre", "]", "[", "1", "]", "predecessors", ".", "append", "(", "(", "pre", ",", "graph", ".", "edge_weight", "(", "(", "pre", ",", "node", ")", ")", "+", "max_pre", ")", ")", "max", "=", "0", "max_tuple", "=", "(", "None", ",", "0", ")", "for", "i", "in", "predecessors", ":", "#look for the most costly predecessor", "if", "i", "[", "1", "]", ">=", "max", ":", "max", "=", "i", "[", "1", "]", "max_tuple", "=", "i", "#assign the maximum value to the given node in the node_tuples dictionary", "node_tuples", "[", "node", "]", "=", "max_tuple", "#find the critical node", "max", "=", "0", "critical_node", "=", "None", "for", "k", ",", "v", "in", "list", "(", "node_tuples", ".", "items", "(", ")", ")", ":", "if", "v", "[", "1", "]", ">=", "max", ":", "max", "=", "v", "[", "1", "]", "critical_node", "=", "k", "path", "=", "[", "]", "#find the critical path with backtracking trought the dictionary", "def", "mid_critical_path", "(", "end", ")", ":", "if", "node_tuples", "[", "end", "]", "[", "0", "]", "!=", "None", ":", "path", ".", "append", "(", "end", ")", "mid_critical_path", "(", "node_tuples", "[", "end", "]", "[", "0", "]", ")", "else", ":", "path", ".", "append", "(", "end", ")", "#call the recursive function", "mid_critical_path", "(", "critical_node", ")", "path", ".", "reverse", "(", ")", "return", "path" ]
Compute and return the critical path in an acyclic directed weighted graph. @attention: This function is only meaningful for directed weighted acyclic graphs @type graph: digraph @param graph: Digraph @rtype: List @return: List containing all the nodes in the path (or an empty array if the graph contains a cycle)
[ "Compute", "and", "return", "the", "critical", "path", "in", "an", "acyclic", "directed", "weighted", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/critical.py#L98-L163