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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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"... | 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 | train | 227,500 |
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",
".",
... | 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 | train | 227,501 |
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",... | 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 | train | 227,502 |
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",
".",
"_resol... | 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 | train | 227,503 |
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... | Validate the context. | [
"Validate",
"the",
"context",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L913-L919 | train | 227,504 |
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",
",",
"paren... | 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 | train | 227,505 |
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",
"]"... | 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 | train | 227,506 |
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",
"=",
"... | 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 | train | 227,507 |
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",
"(",
"s... | 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 | train | 227,508 |
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",
",",
"paren... | 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 | train | 227,509 |
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",
")",
... | 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 | train | 227,510 |
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... | 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 | train | 227,511 |
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",... | 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 | train | 227,512 |
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",
".... | 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 | train | 227,513 |
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",
",",
"bloc... | 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 | train | 227,514 |
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\"",
... | 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 | train | 227,515 |
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 | train | 227,516 |
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",
".",
"_... | 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 | train | 227,517 |
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",
".",
"f... | 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 | train | 227,518 |
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 | train | 227,519 |
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 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 | train | 227,520 |
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",... | 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 | train | 227,521 |
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",
"(",
"(... | 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 | train | 227,522 |
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"... | 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 | train | 227,523 |
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",
")",
"sel... | 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 | train | 227,524 |
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",
".",
... | 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 | train | 227,525 |
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",
"(",
"sel... | 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 | train | 227,526 |
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",
"(",
"\... | 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 | train | 227,527 |
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"... | 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 | train | 227,528 |
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.",... | 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 | train | 227,529 |
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\"",
"#... | 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 | train | 227,530 |
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_... | 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 | train | 227,531 |
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",
... | 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 | train | 227,532 |
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",
"=",
"cod... | 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 | train | 227,533 |
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",
")"... | 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 | train | 227,534 |
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 | train | 227,535 |
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 | train | 227,536 |
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",
... | 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 | train | 227,537 |
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",
... | 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 | train | 227,538 |
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",... | 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 | train | 227,539 |
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",
... | 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 | train | 227,540 |
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 | train | 227,541 |
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 | train | 227,542 |
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",
":",... | 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 | train | 227,543 |
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",
... | 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 | train | 227,544 |
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 | train | 227,545 |
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\"",
")",
... | 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 | train | 227,546 |
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",
"conf... | 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 | train | 227,547 |
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... | 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 | train | 227,548 |
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",
".",
"c... | 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 | train | 227,549 |
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",
... | 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 | train | 227,550 |
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... | 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 | train | 227,551 |
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 | train | 227,552 |
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... | 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 | train | 227,553 |
nerdvegas/rez | src/rezplugins/build_system/custom.py | CustomBuildSystem.build | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables.
"""
ret = {}
if self.write_build_scripts:
# write out the script that places the user in a build env, where
# they can run bez directly themselves.
build_env_script = os.path.join(build_path, "build-env")
create_forwarding_script(build_env_script,
module=("build_system", "custom"),
func_name="_FWD__spawn_build_shell",
working_dir=self.working_dir,
build_path=build_path,
variant_index=variant.index,
install=install,
install_path=install_path)
ret["success"] = True
ret["build_env_script"] = build_env_script
return ret
# get build command
command = self.package.build_command
# False just means no build command
if command is False:
ret["success"] = True
return ret
def expand(txt):
root = self.package.root
install_ = "install" if install else ''
return txt.format(root=root, install=install_).strip()
if isinstance(command, basestring):
if self.build_args:
command = command + ' ' + ' '.join(map(quote, self.build_args))
command = expand(command)
cmd_str = command
else: # list
command = command + self.build_args
command = map(expand, command)
cmd_str = ' '.join(map(quote, command))
if self.verbose:
pr = Printer(sys.stdout)
pr("Running build command: %s" % cmd_str, heading)
# run the build command
def _callback(executor):
self._add_build_actions(executor,
context=context,
package=self.package,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
if self.opts:
# write args defined in ./parse_build_args.py out as env vars
extra_args = getattr(self.opts.parser, "_rezbuild_extra_args", [])
for key, value in vars(self.opts).iteritems():
if key in extra_args:
varname = "__PARSE_ARG_%s" % key.upper()
# do some value conversions
if isinstance(value, bool):
value = 1 if value else 0
elif isinstance(value, (list, tuple)):
value = map(str, value)
value = map(quote, value)
value = ' '.join(value)
executor.env[varname] = value
retcode, _, _ = context.execute_shell(command=command,
block=True,
cwd=build_path,
actions_callback=_callback)
ret["success"] = (not retcode)
return ret | python | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables.
"""
ret = {}
if self.write_build_scripts:
# write out the script that places the user in a build env, where
# they can run bez directly themselves.
build_env_script = os.path.join(build_path, "build-env")
create_forwarding_script(build_env_script,
module=("build_system", "custom"),
func_name="_FWD__spawn_build_shell",
working_dir=self.working_dir,
build_path=build_path,
variant_index=variant.index,
install=install,
install_path=install_path)
ret["success"] = True
ret["build_env_script"] = build_env_script
return ret
# get build command
command = self.package.build_command
# False just means no build command
if command is False:
ret["success"] = True
return ret
def expand(txt):
root = self.package.root
install_ = "install" if install else ''
return txt.format(root=root, install=install_).strip()
if isinstance(command, basestring):
if self.build_args:
command = command + ' ' + ' '.join(map(quote, self.build_args))
command = expand(command)
cmd_str = command
else: # list
command = command + self.build_args
command = map(expand, command)
cmd_str = ' '.join(map(quote, command))
if self.verbose:
pr = Printer(sys.stdout)
pr("Running build command: %s" % cmd_str, heading)
# run the build command
def _callback(executor):
self._add_build_actions(executor,
context=context,
package=self.package,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
if self.opts:
# write args defined in ./parse_build_args.py out as env vars
extra_args = getattr(self.opts.parser, "_rezbuild_extra_args", [])
for key, value in vars(self.opts).iteritems():
if key in extra_args:
varname = "__PARSE_ARG_%s" % key.upper()
# do some value conversions
if isinstance(value, bool):
value = 1 if value else 0
elif isinstance(value, (list, tuple)):
value = map(str, value)
value = map(quote, value)
value = ' '.join(value)
executor.env[varname] = value
retcode, _, _ = context.execute_shell(command=command,
block=True,
cwd=build_path,
actions_callback=_callback)
ret["success"] = (not retcode)
return ret | [
"def",
"build",
"(",
"self",
",",
"context",
",",
"variant",
",",
"build_path",
",",
"install_path",
",",
"install",
"=",
"False",
",",
"build_type",
"=",
"BuildType",
".",
"local",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"self",
".",
"write_build_scripts"... | Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables. | [
"Perform",
"the",
"build",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/build_system/custom.py#L87-L176 | train | 227,554 |
nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS._create_tag_highlevel | def _create_tag_highlevel(self, tag_name, message=None):
"""Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool}
"""
results = []
if self.patch_path:
# make a tag on the patch queue
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=True)
if tagged:
results.append({'type': 'tag', 'patch': True})
# use a bookmark on the main repo since we can't change it
self.hg('bookmark', '-f', tag_name)
results.append({'type': 'bookmark', 'patch': False})
else:
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=False)
if tagged:
results.append({'type': 'tag', 'patch': False})
return results | python | def _create_tag_highlevel(self, tag_name, message=None):
"""Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool}
"""
results = []
if self.patch_path:
# make a tag on the patch queue
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=True)
if tagged:
results.append({'type': 'tag', 'patch': True})
# use a bookmark on the main repo since we can't change it
self.hg('bookmark', '-f', tag_name)
results.append({'type': 'bookmark', 'patch': False})
else:
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=False)
if tagged:
results.append({'type': 'tag', 'patch': False})
return results | [
"def",
"_create_tag_highlevel",
"(",
"self",
",",
"tag_name",
",",
"message",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"self",
".",
"patch_path",
":",
"# make a tag on the patch queue",
"tagged",
"=",
"self",
".",
"_create_tag_lowlevel",
"(",
"ta... | Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool} | [
"Create",
"a",
"tag",
"on",
"the",
"toplevel",
"repo",
"if",
"there",
"is",
"no",
"patch",
"repo",
"or",
"a",
"tag",
"on",
"the",
"patch",
"repo",
"and",
"bookmark",
"on",
"the",
"top",
"repo",
"if",
"there",
"is",
"a",
"patch",
"repo"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L58-L82 | train | 227,555 |
nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS._create_tag_lowlevel | def _create_tag_lowlevel(self, tag_name, message=None, force=True,
patch=False):
"""Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed
"""
# check if tag already exists, and if it does, if it is a direct
# ancestor, and there is NO difference in the files between the tagged
# state and current state
#
# This check is mainly to avoid re-creating the same tag over and over
# on what is essentially the same commit, since tagging will
# technically create a new commit, and update the working copy to it.
#
# Without this check, say you were releasing to three different
# locations, one right after another; the first would create the tag,
# and a new tag commit. The second would then recreate the exact same
# tag, but now pointing at the commit that made the first tag.
# The third would create the tag a THIRD time, but now pointing at the
# commit that created the 2nd tag.
tags = self.get_tags(patch=patch)
old_commit = tags.get(tag_name)
if old_commit is not None:
if not force:
return False
old_rev = old_commit['rev']
# ok, now check to see if direct ancestor...
if self.is_ancestor(old_rev, '.', patch=patch):
# ...and if filestates are same
altered = self.hg('status', '--rev', old_rev, '--rev', '.',
'--no-status')
if not altered or altered == ['.hgtags']:
force = False
if not force:
return False
tag_args = ['tag', tag_name]
if message:
tag_args += ['--message', message]
# we should be ok with ALWAYS having force flag on now, since we should
# have already checked if the commit exists.. but be paranoid, in case
# we've missed some edge case...
if force:
tag_args += ['--force']
self.hg(patch=patch, *tag_args)
return True | python | def _create_tag_lowlevel(self, tag_name, message=None, force=True,
patch=False):
"""Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed
"""
# check if tag already exists, and if it does, if it is a direct
# ancestor, and there is NO difference in the files between the tagged
# state and current state
#
# This check is mainly to avoid re-creating the same tag over and over
# on what is essentially the same commit, since tagging will
# technically create a new commit, and update the working copy to it.
#
# Without this check, say you were releasing to three different
# locations, one right after another; the first would create the tag,
# and a new tag commit. The second would then recreate the exact same
# tag, but now pointing at the commit that made the first tag.
# The third would create the tag a THIRD time, but now pointing at the
# commit that created the 2nd tag.
tags = self.get_tags(patch=patch)
old_commit = tags.get(tag_name)
if old_commit is not None:
if not force:
return False
old_rev = old_commit['rev']
# ok, now check to see if direct ancestor...
if self.is_ancestor(old_rev, '.', patch=patch):
# ...and if filestates are same
altered = self.hg('status', '--rev', old_rev, '--rev', '.',
'--no-status')
if not altered or altered == ['.hgtags']:
force = False
if not force:
return False
tag_args = ['tag', tag_name]
if message:
tag_args += ['--message', message]
# we should be ok with ALWAYS having force flag on now, since we should
# have already checked if the commit exists.. but be paranoid, in case
# we've missed some edge case...
if force:
tag_args += ['--force']
self.hg(patch=patch, *tag_args)
return True | [
"def",
"_create_tag_lowlevel",
"(",
"self",
",",
"tag_name",
",",
"message",
"=",
"None",
",",
"force",
"=",
"True",
",",
"patch",
"=",
"False",
")",
":",
"# check if tag already exists, and if it does, if it is a direct",
"# ancestor, and there is NO difference in the file... | Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed | [
"Create",
"a",
"tag",
"on",
"the",
"toplevel",
"or",
"patch",
"repo"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L84-L137 | train | 227,556 |
nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS.is_ancestor | def is_ancestor(self, commit1, commit2, patch=False):
"""Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself"""
result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2),
"--template", "exists", patch=patch)
return "exists" in result | python | def is_ancestor(self, commit1, commit2, patch=False):
"""Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself"""
result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2),
"--template", "exists", patch=patch)
return "exists" in result | [
"def",
"is_ancestor",
"(",
"self",
",",
"commit1",
",",
"commit2",
",",
"patch",
"=",
"False",
")",
":",
"result",
"=",
"self",
".",
"hg",
"(",
"\"log\"",
",",
"\"-r\"",
",",
"\"first(%s::%s)\"",
"%",
"(",
"commit1",
",",
"commit2",
")",
",",
"\"--temp... | Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself | [
"Returns",
"True",
"if",
"commit1",
"is",
"a",
"direct",
"ancestor",
"of",
"commit2",
"or",
"False",
"otherwise",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L159-L166 | train | 227,557 |
nerdvegas/rez | src/rez/utils/patching.py | get_patched_request | def get_patched_request(requires, patchlist):
"""Apply patch args to a request.
For example, consider:
>>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"])
["foo-6", "bah-8.1"]
>>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"])
["foo-5"]
The following rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request.
"""
# rules from table in docstring above
rules = {
'': (True, True, True ),
'!': (False, False, False),
'~': (False, False, True ),
'^': (True, True, True )
}
requires = [Requirement(x) if not isinstance(x, Requirement) else x
for x in requires]
appended = []
for patch in patchlist:
if patch and patch[0] in ('!', '~', '^'):
ch = patch[0]
name = Requirement(patch[1:]).name
else:
ch = ''
name = Requirement(patch).name
rule = rules[ch]
replaced = (ch == '^')
for i, req in enumerate(requires):
if req is None or req.name != name:
continue
if not req.conflict:
replace = rule[0] # foo
elif not req.weak:
replace = rule[1] # !foo
else:
replace = rule[2] # ~foo
if replace:
if replaced:
requires[i] = None
else:
requires[i] = Requirement(patch)
replaced = True
if not replaced:
appended.append(Requirement(patch))
result = [x for x in requires if x is not None] + appended
return result | python | def get_patched_request(requires, patchlist):
"""Apply patch args to a request.
For example, consider:
>>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"])
["foo-6", "bah-8.1"]
>>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"])
["foo-5"]
The following rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request.
"""
# rules from table in docstring above
rules = {
'': (True, True, True ),
'!': (False, False, False),
'~': (False, False, True ),
'^': (True, True, True )
}
requires = [Requirement(x) if not isinstance(x, Requirement) else x
for x in requires]
appended = []
for patch in patchlist:
if patch and patch[0] in ('!', '~', '^'):
ch = patch[0]
name = Requirement(patch[1:]).name
else:
ch = ''
name = Requirement(patch).name
rule = rules[ch]
replaced = (ch == '^')
for i, req in enumerate(requires):
if req is None or req.name != name:
continue
if not req.conflict:
replace = rule[0] # foo
elif not req.weak:
replace = rule[1] # !foo
else:
replace = rule[2] # ~foo
if replace:
if replaced:
requires[i] = None
else:
requires[i] = Requirement(patch)
replaced = True
if not replaced:
appended.append(Requirement(patch))
result = [x for x in requires if x is not None] + appended
return result | [
"def",
"get_patched_request",
"(",
"requires",
",",
"patchlist",
")",
":",
"# rules from table in docstring above",
"rules",
"=",
"{",
"''",
":",
"(",
"True",
",",
"True",
",",
"True",
")",
",",
"'!'",
":",
"(",
"False",
",",
"False",
",",
"False",
")",
... | Apply patch args to a request.
For example, consider:
>>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"])
["foo-6", "bah-8.1"]
>>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"])
["foo-5"]
The following rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request. | [
"Apply",
"patch",
"args",
"to",
"a",
"request",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/patching.py#L4-L78 | train | 227,558 |
nerdvegas/rez | src/support/shotgun_toolkit/rez_app_launch.py | AppLaunch.execute | def execute(self, app_path, app_args, version, **kwargs):
"""
The execute functon of the hook will be called to start the required application
:param app_path: (str) The path of the application executable
:param app_args: (str) Any arguments the application may require
:param version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int).
"""
multi_launchapp = self.parent
extra = multi_launchapp.get_setting("extra")
use_rez = False
if self.check_rez():
from rez.resolved_context import ResolvedContext
from rez.config import config
# Define variables used to bootstrap tank from overwrite on first reference
# PYTHONPATH is used by tk-maya
# NUKE_PATH is used by tk-nuke
# HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio)
# KATANA_RESOURCES is used by tk-katana
config.parent_variables = ["PYTHONPATH", "HOUDINI_PATH", "NUKE_PATH", "HIERO_PLUGIN_PATH", "KATANA_RESOURCES"]
rez_packages = extra["rez_packages"]
context = ResolvedContext(rez_packages)
use_rez = True
system = sys.platform
shell_type = 'bash'
if system == "linux2":
# on linux, we just run the executable directly
cmd = "%s %s &" % (app_path, app_args)
elif self.parent.get_setting("engine") in ["tk-flame", "tk-flare"]:
# flame and flare works in a different way from other DCCs
# on both linux and mac, they run unix-style command line
# and on the mac the more standardized "open" command cannot
# be utilized.
cmd = "%s %s &" % (app_path, app_args)
elif system == "darwin":
# on the mac, the executable paths are normally pointing
# to the application bundle and not to the binary file
# embedded in the bundle, meaning that we should use the
# built-in mac open command to execute it
cmd = "open -n \"%s\"" % (app_path)
if app_args:
cmd += " --args \"%s\"" % app_args.replace("\"", "\\\"")
elif system == "win32":
# on windows, we run the start command in order to avoid
# any command shells popping up as part of the application launch.
cmd = "start /B \"App\" \"%s\" %s" % (app_path, app_args)
shell_type = 'cmd'
# Execute App in a Rez context
if use_rez:
n_env = os.environ.copy()
proc = context.execute_shell(
command=cmd,
parent_environ=n_env,
shell=shell_type,
stdin=False,
block=False
)
exit_code = proc.wait()
context.print_info(verbosity=True)
else:
# run the command to launch the app
exit_code = os.system(cmd)
return {
"command": cmd,
"return_code": exit_code
} | python | def execute(self, app_path, app_args, version, **kwargs):
"""
The execute functon of the hook will be called to start the required application
:param app_path: (str) The path of the application executable
:param app_args: (str) Any arguments the application may require
:param version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int).
"""
multi_launchapp = self.parent
extra = multi_launchapp.get_setting("extra")
use_rez = False
if self.check_rez():
from rez.resolved_context import ResolvedContext
from rez.config import config
# Define variables used to bootstrap tank from overwrite on first reference
# PYTHONPATH is used by tk-maya
# NUKE_PATH is used by tk-nuke
# HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio)
# KATANA_RESOURCES is used by tk-katana
config.parent_variables = ["PYTHONPATH", "HOUDINI_PATH", "NUKE_PATH", "HIERO_PLUGIN_PATH", "KATANA_RESOURCES"]
rez_packages = extra["rez_packages"]
context = ResolvedContext(rez_packages)
use_rez = True
system = sys.platform
shell_type = 'bash'
if system == "linux2":
# on linux, we just run the executable directly
cmd = "%s %s &" % (app_path, app_args)
elif self.parent.get_setting("engine") in ["tk-flame", "tk-flare"]:
# flame and flare works in a different way from other DCCs
# on both linux and mac, they run unix-style command line
# and on the mac the more standardized "open" command cannot
# be utilized.
cmd = "%s %s &" % (app_path, app_args)
elif system == "darwin":
# on the mac, the executable paths are normally pointing
# to the application bundle and not to the binary file
# embedded in the bundle, meaning that we should use the
# built-in mac open command to execute it
cmd = "open -n \"%s\"" % (app_path)
if app_args:
cmd += " --args \"%s\"" % app_args.replace("\"", "\\\"")
elif system == "win32":
# on windows, we run the start command in order to avoid
# any command shells popping up as part of the application launch.
cmd = "start /B \"App\" \"%s\" %s" % (app_path, app_args)
shell_type = 'cmd'
# Execute App in a Rez context
if use_rez:
n_env = os.environ.copy()
proc = context.execute_shell(
command=cmd,
parent_environ=n_env,
shell=shell_type,
stdin=False,
block=False
)
exit_code = proc.wait()
context.print_info(verbosity=True)
else:
# run the command to launch the app
exit_code = os.system(cmd)
return {
"command": cmd,
"return_code": exit_code
} | [
"def",
"execute",
"(",
"self",
",",
"app_path",
",",
"app_args",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"multi_launchapp",
"=",
"self",
".",
"parent",
"extra",
"=",
"multi_launchapp",
".",
"get_setting",
"(",
"\"extra\"",
")",
"use_rez",
"=",
... | The execute functon of the hook will be called to start the required application
:param app_path: (str) The path of the application executable
:param app_args: (str) Any arguments the application may require
:param version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int). | [
"The",
"execute",
"functon",
"of",
"the",
"hook",
"will",
"be",
"called",
"to",
"start",
"the",
"required",
"application"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/shotgun_toolkit/rez_app_launch.py#L37-L117 | train | 227,559 |
nerdvegas/rez | src/support/shotgun_toolkit/rez_app_launch.py | AppLaunch.check_rez | def check_rez(self, strict=True):
"""
Checks to see if a Rez package is available in the current environment.
If it is available, add it to the system path, exposing the Rez Python API
:param strict: (bool) If True, raise an error if Rez is not available as a package.
This will prevent the app from being launched.
:returns: A path to the Rez package.
"""
system = sys.platform
if system == "win32":
rez_cmd = 'rez-env rez -- echo %REZ_REZ_ROOT%'
else:
rez_cmd = 'rez-env rez -- printenv REZ_REZ_ROOT'
process = subprocess.Popen(rez_cmd, stdout=subprocess.PIPE, shell=True)
rez_path, err = process.communicate()
if err or not rez_path:
if strict:
raise ImportError("Failed to find Rez as a package in the current "
"environment! Try 'rez-bind rez'!")
else:
print >> sys.stderr, ("WARNING: Failed to find a Rez package in the current "
"environment. Unable to request Rez packages.")
rez_path = ""
else:
rez_path = rez_path.strip()
print "Found Rez:", rez_path
print "Adding Rez to system path..."
sys.path.append(rez_path)
return rez_path | python | def check_rez(self, strict=True):
"""
Checks to see if a Rez package is available in the current environment.
If it is available, add it to the system path, exposing the Rez Python API
:param strict: (bool) If True, raise an error if Rez is not available as a package.
This will prevent the app from being launched.
:returns: A path to the Rez package.
"""
system = sys.platform
if system == "win32":
rez_cmd = 'rez-env rez -- echo %REZ_REZ_ROOT%'
else:
rez_cmd = 'rez-env rez -- printenv REZ_REZ_ROOT'
process = subprocess.Popen(rez_cmd, stdout=subprocess.PIPE, shell=True)
rez_path, err = process.communicate()
if err or not rez_path:
if strict:
raise ImportError("Failed to find Rez as a package in the current "
"environment! Try 'rez-bind rez'!")
else:
print >> sys.stderr, ("WARNING: Failed to find a Rez package in the current "
"environment. Unable to request Rez packages.")
rez_path = ""
else:
rez_path = rez_path.strip()
print "Found Rez:", rez_path
print "Adding Rez to system path..."
sys.path.append(rez_path)
return rez_path | [
"def",
"check_rez",
"(",
"self",
",",
"strict",
"=",
"True",
")",
":",
"system",
"=",
"sys",
".",
"platform",
"if",
"system",
"==",
"\"win32\"",
":",
"rez_cmd",
"=",
"'rez-env rez -- echo %REZ_REZ_ROOT%'",
"else",
":",
"rez_cmd",
"=",
"'rez-env rez -- printenv R... | Checks to see if a Rez package is available in the current environment.
If it is available, add it to the system path, exposing the Rez Python API
:param strict: (bool) If True, raise an error if Rez is not available as a package.
This will prevent the app from being launched.
:returns: A path to the Rez package. | [
"Checks",
"to",
"see",
"if",
"a",
"Rez",
"package",
"is",
"available",
"in",
"the",
"current",
"environment",
".",
"If",
"it",
"is",
"available",
"add",
"it",
"to",
"the",
"system",
"path",
"exposing",
"the",
"Rez",
"Python",
"API"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/shotgun_toolkit/rez_app_launch.py#L119-L155 | train | 227,560 |
nerdvegas/rez | src/rezplugins/release_vcs/svn.py | get_last_changed_revision | def get_last_changed_revision(client, url):
"""
util func, get last revision of url
"""
try:
svn_entries = client.info2(url,
pysvn.Revision(pysvn.opt_revision_kind.head),
recurse=False)
if not svn_entries:
raise ReleaseVCSError("svn.info2() returned no results on url %s" % url)
return svn_entries[0][1].last_changed_rev
except pysvn.ClientError, ce:
raise ReleaseVCSError("svn.info2() raised ClientError: %s" % ce) | python | def get_last_changed_revision(client, url):
"""
util func, get last revision of url
"""
try:
svn_entries = client.info2(url,
pysvn.Revision(pysvn.opt_revision_kind.head),
recurse=False)
if not svn_entries:
raise ReleaseVCSError("svn.info2() returned no results on url %s" % url)
return svn_entries[0][1].last_changed_rev
except pysvn.ClientError, ce:
raise ReleaseVCSError("svn.info2() raised ClientError: %s" % ce) | [
"def",
"get_last_changed_revision",
"(",
"client",
",",
"url",
")",
":",
"try",
":",
"svn_entries",
"=",
"client",
".",
"info2",
"(",
"url",
",",
"pysvn",
".",
"Revision",
"(",
"pysvn",
".",
"opt_revision_kind",
".",
"head",
")",
",",
"recurse",
"=",
"Fa... | util func, get last revision of url | [
"util",
"func",
"get",
"last",
"revision",
"of",
"url"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/svn.py#L26-L38 | train | 227,561 |
nerdvegas/rez | src/rezplugins/release_vcs/svn.py | get_svn_login | def get_svn_login(realm, username, may_save):
"""
provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc.
"""
import getpass
print "svn requires a password for the user %s:" % username
pwd = ''
while not pwd.strip():
pwd = getpass.getpass("--> ")
return True, username, pwd, False | python | def get_svn_login(realm, username, may_save):
"""
provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc.
"""
import getpass
print "svn requires a password for the user %s:" % username
pwd = ''
while not pwd.strip():
pwd = getpass.getpass("--> ")
return True, username, pwd, False | [
"def",
"get_svn_login",
"(",
"realm",
",",
"username",
",",
"may_save",
")",
":",
"import",
"getpass",
"print",
"\"svn requires a password for the user %s:\"",
"%",
"username",
"pwd",
"=",
"''",
"while",
"not",
"pwd",
".",
"strip",
"(",
")",
":",
"pwd",
"=",
... | provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc. | [
"provide",
"svn",
"with",
"permissions",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/svn.py#L41-L53 | train | 227,562 |
nerdvegas/rez | src/rez/vendor/pygraph/readwrite/markup.py | read | def read(string):
"""
Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph
"""
dom = parseString(string)
if dom.getElementsByTagName("graph"):
G = graph()
elif dom.getElementsByTagName("digraph"):
G = digraph()
elif dom.getElementsByTagName("hypergraph"):
return read_hypergraph(string)
else:
raise InvalidGraphType
# Read nodes...
for each_node in dom.getElementsByTagName("node"):
G.add_node(each_node.getAttribute('id'))
for each_attr in each_node.getElementsByTagName("attribute"):
G.add_node_attribute(each_node.getAttribute('id'),
(each_attr.getAttribute('attr'),
each_attr.getAttribute('value')))
# Read edges...
for each_edge in dom.getElementsByTagName("edge"):
if (not G.has_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')))):
G.add_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')), \
wt = float(each_edge.getAttribute('wt')), label = each_edge.getAttribute('label'))
for each_attr in each_edge.getElementsByTagName("attribute"):
attr_tuple = (each_attr.getAttribute('attr'), each_attr.getAttribute('value'))
if (attr_tuple not in G.edge_attributes((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')))):
G.add_edge_attribute((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')), attr_tuple)
return G | python | def read(string):
"""
Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph
"""
dom = parseString(string)
if dom.getElementsByTagName("graph"):
G = graph()
elif dom.getElementsByTagName("digraph"):
G = digraph()
elif dom.getElementsByTagName("hypergraph"):
return read_hypergraph(string)
else:
raise InvalidGraphType
# Read nodes...
for each_node in dom.getElementsByTagName("node"):
G.add_node(each_node.getAttribute('id'))
for each_attr in each_node.getElementsByTagName("attribute"):
G.add_node_attribute(each_node.getAttribute('id'),
(each_attr.getAttribute('attr'),
each_attr.getAttribute('value')))
# Read edges...
for each_edge in dom.getElementsByTagName("edge"):
if (not G.has_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')))):
G.add_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')), \
wt = float(each_edge.getAttribute('wt')), label = each_edge.getAttribute('label'))
for each_attr in each_edge.getElementsByTagName("attribute"):
attr_tuple = (each_attr.getAttribute('attr'), each_attr.getAttribute('value'))
if (attr_tuple not in G.edge_attributes((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')))):
G.add_edge_attribute((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')), attr_tuple)
return G | [
"def",
"read",
"(",
"string",
")",
":",
"dom",
"=",
"parseString",
"(",
"string",
")",
"if",
"dom",
".",
"getElementsByTagName",
"(",
"\"graph\"",
")",
":",
"G",
"=",
"graph",
"(",
")",
"elif",
"dom",
".",
"getElementsByTagName",
"(",
"\"digraph\"",
")",... | Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph | [
"Read",
"a",
"graph",
"from",
"a",
"XML",
"document",
"and",
"return",
"it",
".",
"Nodes",
"and",
"edges",
"specified",
"in",
"the",
"input",
"will",
"be",
"added",
"to",
"the",
"current",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/markup.py#L91-L132 | train | 227,563 |
nerdvegas/rez | src/rez/vendor/pygraph/readwrite/markup.py | read_hypergraph | def read_hypergraph(string):
"""
Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph
"""
hgr = hypergraph()
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
hgr.add_node(each_node.getAttribute('id'))
for each_node in dom.getElementsByTagName("hyperedge"):
hgr.add_hyperedge(each_node.getAttribute('id'))
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
for each_edge in each_node.getElementsByTagName("link"):
hgr.link(str(each_node.getAttribute('id')), str(each_edge.getAttribute('to')))
return hgr | python | def read_hypergraph(string):
"""
Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph
"""
hgr = hypergraph()
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
hgr.add_node(each_node.getAttribute('id'))
for each_node in dom.getElementsByTagName("hyperedge"):
hgr.add_hyperedge(each_node.getAttribute('id'))
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
for each_edge in each_node.getElementsByTagName("link"):
hgr.link(str(each_node.getAttribute('id')), str(each_edge.getAttribute('to')))
return hgr | [
"def",
"read_hypergraph",
"(",
"string",
")",
":",
"hgr",
"=",
"hypergraph",
"(",
")",
"dom",
"=",
"parseString",
"(",
"string",
")",
"for",
"each_node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"\"node\"",
")",
":",
"hgr",
".",
"add_node",
"(",
"e... | Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph | [
"Read",
"a",
"graph",
"from",
"a",
"XML",
"document",
".",
"Nodes",
"and",
"hyperedges",
"specified",
"in",
"the",
"input",
"will",
"be",
"added",
"to",
"the",
"current",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/markup.py#L172-L195 | train | 227,564 |
nerdvegas/rez | src/rez/utils/diff_packages.py | diff_packages | def diff_packages(pkg1, pkg2=None):
"""Invoke a diff editor to show the difference between the source of two
packages.
Args:
pkg1 (`Package`): Package to diff.
pkg2 (`Package`): Package to diff against. If None, the next most recent
package version is used.
"""
if pkg2 is None:
it = iter_packages(pkg1.name)
pkgs = [x for x in it if x.version < pkg1.version]
if not pkgs:
raise RezError("No package to diff with - %s is the earliest "
"package version" % pkg1.qualified_name)
pkgs = sorted(pkgs, key=lambda x: x.version)
pkg2 = pkgs[-1]
def _check_pkg(pkg):
if not (pkg.vcs and pkg.revision):
raise RezError("Cannot diff package %s: it is a legacy format "
"package that does not contain enough information"
% pkg.qualified_name)
_check_pkg(pkg1)
_check_pkg(pkg2)
path = mkdtemp(prefix="rez-pkg-diff")
paths = []
for pkg in (pkg1, pkg2):
print "Exporting %s..." % pkg.qualified_name
path_ = os.path.join(path, pkg.qualified_name)
vcs_cls_1 = plugin_manager.get_plugin_class("release_vcs", pkg1.vcs)
vcs_cls_1.export(revision=pkg.revision, path=path_)
paths.append(path_)
difftool = config.difftool
print "Opening diff viewer %s..." % difftool
proc = Popen([difftool] + paths)
proc.wait() | python | def diff_packages(pkg1, pkg2=None):
"""Invoke a diff editor to show the difference between the source of two
packages.
Args:
pkg1 (`Package`): Package to diff.
pkg2 (`Package`): Package to diff against. If None, the next most recent
package version is used.
"""
if pkg2 is None:
it = iter_packages(pkg1.name)
pkgs = [x for x in it if x.version < pkg1.version]
if not pkgs:
raise RezError("No package to diff with - %s is the earliest "
"package version" % pkg1.qualified_name)
pkgs = sorted(pkgs, key=lambda x: x.version)
pkg2 = pkgs[-1]
def _check_pkg(pkg):
if not (pkg.vcs and pkg.revision):
raise RezError("Cannot diff package %s: it is a legacy format "
"package that does not contain enough information"
% pkg.qualified_name)
_check_pkg(pkg1)
_check_pkg(pkg2)
path = mkdtemp(prefix="rez-pkg-diff")
paths = []
for pkg in (pkg1, pkg2):
print "Exporting %s..." % pkg.qualified_name
path_ = os.path.join(path, pkg.qualified_name)
vcs_cls_1 = plugin_manager.get_plugin_class("release_vcs", pkg1.vcs)
vcs_cls_1.export(revision=pkg.revision, path=path_)
paths.append(path_)
difftool = config.difftool
print "Opening diff viewer %s..." % difftool
proc = Popen([difftool] + paths)
proc.wait() | [
"def",
"diff_packages",
"(",
"pkg1",
",",
"pkg2",
"=",
"None",
")",
":",
"if",
"pkg2",
"is",
"None",
":",
"it",
"=",
"iter_packages",
"(",
"pkg1",
".",
"name",
")",
"pkgs",
"=",
"[",
"x",
"for",
"x",
"in",
"it",
"if",
"x",
".",
"version",
"<",
... | Invoke a diff editor to show the difference between the source of two
packages.
Args:
pkg1 (`Package`): Package to diff.
pkg2 (`Package`): Package to diff against. If None, the next most recent
package version is used. | [
"Invoke",
"a",
"diff",
"editor",
"to",
"show",
"the",
"difference",
"between",
"the",
"source",
"of",
"two",
"packages",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/diff_packages.py#L10-L49 | train | 227,565 |
nerdvegas/rez | src/rez/cli/_util.py | sigint_handler | def sigint_handler(signum, frame):
"""Exit gracefully on ctrl-C."""
global _handled_int
if not _handled_int:
_handled_int = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Interrupted by user"
sigbase_handler(signum, frame) | python | def sigint_handler(signum, frame):
"""Exit gracefully on ctrl-C."""
global _handled_int
if not _handled_int:
_handled_int = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Interrupted by user"
sigbase_handler(signum, frame) | [
"def",
"sigint_handler",
"(",
"signum",
",",
"frame",
")",
":",
"global",
"_handled_int",
"if",
"not",
"_handled_int",
":",
"_handled_int",
"=",
"True",
"if",
"not",
"_env_var_true",
"(",
"\"_REZ_QUIET_ON_SIG\"",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
... | Exit gracefully on ctrl-C. | [
"Exit",
"gracefully",
"on",
"ctrl",
"-",
"C",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L141-L148 | train | 227,566 |
nerdvegas/rez | src/rez/cli/_util.py | sigterm_handler | def sigterm_handler(signum, frame):
"""Exit gracefully on terminate."""
global _handled_term
if not _handled_term:
_handled_term = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Terminated by user"
sigbase_handler(signum, frame) | python | def sigterm_handler(signum, frame):
"""Exit gracefully on terminate."""
global _handled_term
if not _handled_term:
_handled_term = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Terminated by user"
sigbase_handler(signum, frame) | [
"def",
"sigterm_handler",
"(",
"signum",
",",
"frame",
")",
":",
"global",
"_handled_term",
"if",
"not",
"_handled_term",
":",
"_handled_term",
"=",
"True",
"if",
"not",
"_env_var_true",
"(",
"\"_REZ_QUIET_ON_SIG\"",
")",
":",
"print",
">>",
"sys",
".",
"stder... | Exit gracefully on terminate. | [
"Exit",
"gracefully",
"on",
"terminate",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L151-L158 | train | 227,567 |
nerdvegas/rez | src/rez/cli/_util.py | LazyArgumentParser.format_help | def format_help(self):
"""Sets up all sub-parsers when help is requested."""
if self._subparsers:
for action in self._subparsers._actions:
if isinstance(action, LazySubParsersAction):
for parser_name, parser in action._name_parser_map.iteritems():
action._setup_subparser(parser_name, parser)
return super(LazyArgumentParser, self).format_help() | python | def format_help(self):
"""Sets up all sub-parsers when help is requested."""
if self._subparsers:
for action in self._subparsers._actions:
if isinstance(action, LazySubParsersAction):
for parser_name, parser in action._name_parser_map.iteritems():
action._setup_subparser(parser_name, parser)
return super(LazyArgumentParser, self).format_help() | [
"def",
"format_help",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subparsers",
":",
"for",
"action",
"in",
"self",
".",
"_subparsers",
".",
"_actions",
":",
"if",
"isinstance",
"(",
"action",
",",
"LazySubParsersAction",
")",
":",
"for",
"parser_name",
","... | Sets up all sub-parsers when help is requested. | [
"Sets",
"up",
"all",
"sub",
"-",
"parsers",
"when",
"help",
"is",
"requested",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L110-L117 | train | 227,568 |
nerdvegas/rez | src/rez/utils/formatting.py | is_valid_package_name | def is_valid_package_name(name, raise_error=False):
"""Test the validity of a package name string.
Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure
Returns:
bool.
"""
is_valid = PACKAGE_NAME_REGEX.match(name)
if raise_error and not is_valid:
raise PackageRequestError("Not a valid package name: %r" % name)
return is_valid | python | def is_valid_package_name(name, raise_error=False):
"""Test the validity of a package name string.
Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure
Returns:
bool.
"""
is_valid = PACKAGE_NAME_REGEX.match(name)
if raise_error and not is_valid:
raise PackageRequestError("Not a valid package name: %r" % name)
return is_valid | [
"def",
"is_valid_package_name",
"(",
"name",
",",
"raise_error",
"=",
"False",
")",
":",
"is_valid",
"=",
"PACKAGE_NAME_REGEX",
".",
"match",
"(",
"name",
")",
"if",
"raise_error",
"and",
"not",
"is_valid",
":",
"raise",
"PackageRequestError",
"(",
"\"Not a vali... | Test the validity of a package name string.
Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure
Returns:
bool. | [
"Test",
"the",
"validity",
"of",
"a",
"package",
"name",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L27-L40 | train | 227,569 |
nerdvegas/rez | src/rez/utils/formatting.py | expand_abbreviations | def expand_abbreviations(txt, fields):
"""Expand abbreviations in a format string.
If an abbreviation does not match a field, or matches multiple fields, it
is left unchanged.
Example:
>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string.
"""
def _expand(matchobj):
s = matchobj.group("var")
if s not in fields:
matches = [x for x in fields if x.startswith(s)]
if len(matches) == 1:
s = matches[0]
return "{%s}" % s
return re.sub(FORMAT_VAR_REGEX, _expand, txt) | python | def expand_abbreviations(txt, fields):
"""Expand abbreviations in a format string.
If an abbreviation does not match a field, or matches multiple fields, it
is left unchanged.
Example:
>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string.
"""
def _expand(matchobj):
s = matchobj.group("var")
if s not in fields:
matches = [x for x in fields if x.startswith(s)]
if len(matches) == 1:
s = matches[0]
return "{%s}" % s
return re.sub(FORMAT_VAR_REGEX, _expand, txt) | [
"def",
"expand_abbreviations",
"(",
"txt",
",",
"fields",
")",
":",
"def",
"_expand",
"(",
"matchobj",
")",
":",
"s",
"=",
"matchobj",
".",
"group",
"(",
"\"var\"",
")",
"if",
"s",
"not",
"in",
"fields",
":",
"matches",
"=",
"[",
"x",
"for",
"x",
"... | Expand abbreviations in a format string.
If an abbreviation does not match a field, or matches multiple fields, it
is left unchanged.
Example:
>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string. | [
"Expand",
"abbreviations",
"in",
"a",
"format",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L174-L200 | train | 227,570 |
nerdvegas/rez | src/rez/utils/formatting.py | dict_to_attributes_code | def dict_to_attributes_code(dict_):
"""Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str.
"""
lines = []
for key, value in dict_.iteritems():
if isinstance(value, dict):
txt = dict_to_attributes_code(value)
lines_ = txt.split('\n')
for line in lines_:
if not line.startswith(' '):
line = "%s.%s" % (key, line)
lines.append(line)
else:
value_txt = pformat(value)
if '\n' in value_txt:
lines.append("%s = \\" % key)
value_txt = indent(value_txt)
lines.extend(value_txt.split('\n'))
else:
line = "%s = %s" % (key, value_txt)
lines.append(line)
return '\n'.join(lines) | python | def dict_to_attributes_code(dict_):
"""Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str.
"""
lines = []
for key, value in dict_.iteritems():
if isinstance(value, dict):
txt = dict_to_attributes_code(value)
lines_ = txt.split('\n')
for line in lines_:
if not line.startswith(' '):
line = "%s.%s" % (key, line)
lines.append(line)
else:
value_txt = pformat(value)
if '\n' in value_txt:
lines.append("%s = \\" % key)
value_txt = indent(value_txt)
lines.extend(value_txt.split('\n'))
else:
line = "%s = %s" % (key, value_txt)
lines.append(line)
return '\n'.join(lines) | [
"def",
"dict_to_attributes_code",
"(",
"dict_",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"dict_",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"txt",
"=",
"dict_to_attributes_code",
... | Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str. | [
"Given",
"a",
"nested",
"dict",
"generate",
"a",
"python",
"code",
"equivalent",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L247-L279 | train | 227,571 |
nerdvegas/rez | src/rez/utils/formatting.py | columnise | def columnise(rows, padding=2):
"""Print rows of entries in aligned columns."""
strs = []
maxwidths = {}
for row in rows:
for i, e in enumerate(row):
se = str(e)
nse = len(se)
w = maxwidths.get(i, -1)
if nse > w:
maxwidths[i] = nse
for row in rows:
s = ''
for i, e in enumerate(row):
se = str(e)
if i < len(row) - 1:
n = maxwidths[i] + padding - len(se)
se += ' ' * n
s += se
strs.append(s)
return strs | python | def columnise(rows, padding=2):
"""Print rows of entries in aligned columns."""
strs = []
maxwidths = {}
for row in rows:
for i, e in enumerate(row):
se = str(e)
nse = len(se)
w = maxwidths.get(i, -1)
if nse > w:
maxwidths[i] = nse
for row in rows:
s = ''
for i, e in enumerate(row):
se = str(e)
if i < len(row) - 1:
n = maxwidths[i] + padding - len(se)
se += ' ' * n
s += se
strs.append(s)
return strs | [
"def",
"columnise",
"(",
"rows",
",",
"padding",
"=",
"2",
")",
":",
"strs",
"=",
"[",
"]",
"maxwidths",
"=",
"{",
"}",
"for",
"row",
"in",
"rows",
":",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"row",
")",
":",
"se",
"=",
"str",
"(",
"e"... | Print rows of entries in aligned columns. | [
"Print",
"rows",
"of",
"entries",
"in",
"aligned",
"columns",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L282-L304 | train | 227,572 |
nerdvegas/rez | src/rez/utils/formatting.py | print_colored_columns | def print_colored_columns(printer, rows, padding=2):
"""Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring.
"""
rows_ = [x[:-1] for x in rows]
colors = [x[-1] for x in rows]
for col, line in zip(colors, columnise(rows_, padding=padding)):
printer(line, col) | python | def print_colored_columns(printer, rows, padding=2):
"""Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring.
"""
rows_ = [x[:-1] for x in rows]
colors = [x[-1] for x in rows]
for col, line in zip(colors, columnise(rows_, padding=padding)):
printer(line, col) | [
"def",
"print_colored_columns",
"(",
"printer",
",",
"rows",
",",
"padding",
"=",
"2",
")",
":",
"rows_",
"=",
"[",
"x",
"[",
":",
"-",
"1",
"]",
"for",
"x",
"in",
"rows",
"]",
"colors",
"=",
"[",
"x",
"[",
"-",
"1",
"]",
"for",
"x",
"in",
"r... | Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring. | [
"Like",
"columnise",
"but",
"with",
"colored",
"rows",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L307-L319 | train | 227,573 |
nerdvegas/rez | src/rez/utils/formatting.py | expanduser | def expanduser(path):
"""Expand '~' to home directory in the given string.
Note that this function deliberately differs from the builtin
os.path.expanduser() on Linux systems, which expands strings such as
'~sclaus' to that user's homedir. This is problematic in rez because the
string '~packagename' may inadvertently convert to a homedir, if a package
happens to match a username.
"""
if '~' not in path:
return path
if os.name == "nt":
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH' in os.environ:
drive = os.environ.get('HOMEDRIVE', '')
userhome = os.path.join(drive, os.environ['HOMEPATH'])
else:
return path
else:
userhome = os.path.expanduser('~')
def _expanduser(path):
return EXPANDUSER_RE.sub(
lambda m: m.groups()[0] + userhome + m.groups()[1],
path)
# only replace '~' if it's at start of string or is preceeded by pathsep or
# ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or
# end-of-string.
#
return os.path.normpath(_expanduser(path)) | python | def expanduser(path):
"""Expand '~' to home directory in the given string.
Note that this function deliberately differs from the builtin
os.path.expanduser() on Linux systems, which expands strings such as
'~sclaus' to that user's homedir. This is problematic in rez because the
string '~packagename' may inadvertently convert to a homedir, if a package
happens to match a username.
"""
if '~' not in path:
return path
if os.name == "nt":
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH' in os.environ:
drive = os.environ.get('HOMEDRIVE', '')
userhome = os.path.join(drive, os.environ['HOMEPATH'])
else:
return path
else:
userhome = os.path.expanduser('~')
def _expanduser(path):
return EXPANDUSER_RE.sub(
lambda m: m.groups()[0] + userhome + m.groups()[1],
path)
# only replace '~' if it's at start of string or is preceeded by pathsep or
# ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or
# end-of-string.
#
return os.path.normpath(_expanduser(path)) | [
"def",
"expanduser",
"(",
"path",
")",
":",
"if",
"'~'",
"not",
"in",
"path",
":",
"return",
"path",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"userhome",
"=",
"os",
".",
"environ",
"[",
"'HOME'"... | Expand '~' to home directory in the given string.
Note that this function deliberately differs from the builtin
os.path.expanduser() on Linux systems, which expands strings such as
'~sclaus' to that user's homedir. This is problematic in rez because the
string '~packagename' may inadvertently convert to a homedir, if a package
happens to match a username. | [
"Expand",
"~",
"to",
"home",
"directory",
"in",
"the",
"given",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L439-L473 | train | 227,574 |
nerdvegas/rez | src/rez/utils/formatting.py | as_block_string | def as_block_string(txt):
"""Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary.
"""
import json
lines = []
for line in txt.split('\n'):
line_ = json.dumps(line)
line_ = line_[1:-1].rstrip() # drop double quotes
lines.append(line_)
return '"""\n%s\n"""' % '\n'.join(lines) | python | def as_block_string(txt):
"""Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary.
"""
import json
lines = []
for line in txt.split('\n'):
line_ = json.dumps(line)
line_ = line_[1:-1].rstrip() # drop double quotes
lines.append(line_)
return '"""\n%s\n"""' % '\n'.join(lines) | [
"def",
"as_block_string",
"(",
"txt",
")",
":",
"import",
"json",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"txt",
".",
"split",
"(",
"'\\n'",
")",
":",
"line_",
"=",
"json",
".",
"dumps",
"(",
"line",
")",
"line_",
"=",
"line_",
"[",
"1",
":"... | Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary. | [
"Return",
"a",
"string",
"formatted",
"as",
"a",
"python",
"block",
"comment",
"string",
"like",
"the",
"one",
"you",
"re",
"currently",
"reading",
".",
"Special",
"characters",
"are",
"escaped",
"if",
"necessary",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L476-L488 | train | 227,575 |
nerdvegas/rez | src/rez/utils/formatting.py | StringFormatMixin.format | def format(self, s, pretty=None, expand=None):
"""Format a string.
Args:
s (str): String to format, eg "hello {name}"
pretty (bool): If True, references to non-string attributes such as
lists are converted to basic form, with characters such as
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string.
"""
if pretty is None:
pretty = self.format_pretty
if expand is None:
expand = self.format_expand
formatter = ObjectStringFormatter(self, pretty=pretty, expand=expand)
return formatter.format(s) | python | def format(self, s, pretty=None, expand=None):
"""Format a string.
Args:
s (str): String to format, eg "hello {name}"
pretty (bool): If True, references to non-string attributes such as
lists are converted to basic form, with characters such as
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string.
"""
if pretty is None:
pretty = self.format_pretty
if expand is None:
expand = self.format_expand
formatter = ObjectStringFormatter(self, pretty=pretty, expand=expand)
return formatter.format(s) | [
"def",
"format",
"(",
"self",
",",
"s",
",",
"pretty",
"=",
"None",
",",
"expand",
"=",
"None",
")",
":",
"if",
"pretty",
"is",
"None",
":",
"pretty",
"=",
"self",
".",
"format_pretty",
"if",
"expand",
"is",
"None",
":",
"expand",
"=",
"self",
".",... | Format a string.
Args:
s (str): String to format, eg "hello {name}"
pretty (bool): If True, references to non-string attributes such as
lists are converted to basic form, with characters such as
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string. | [
"Format",
"a",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L150-L171 | train | 227,576 |
nerdvegas/rez | src/rez/vendor/version/version.py | Version.copy | def copy(self):
"""Returns a copy of the version."""
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | python | def copy(self):
"""Returns a copy of the version."""
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"Version",
"(",
"None",
")",
"other",
".",
"tokens",
"=",
"self",
".",
"tokens",
"[",
":",
"]",
"other",
".",
"seps",
"=",
"self",
".",
"seps",
"[",
":",
"]",
"return",
"other"
] | Returns a copy of the version. | [
"Returns",
"a",
"copy",
"of",
"the",
"version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L297-L302 | train | 227,577 |
nerdvegas/rez | src/rez/vendor/version/version.py | Version.trim | def trim(self, len_):
"""Return a copy of the version, possibly with less tokens.
Args:
len_ (int): New version length. If >= current length, an
unchanged copy of the version is returned.
"""
other = Version(None)
other.tokens = self.tokens[:len_]
other.seps = self.seps[:len_ - 1]
return other | python | def trim(self, len_):
"""Return a copy of the version, possibly with less tokens.
Args:
len_ (int): New version length. If >= current length, an
unchanged copy of the version is returned.
"""
other = Version(None)
other.tokens = self.tokens[:len_]
other.seps = self.seps[:len_ - 1]
return other | [
"def",
"trim",
"(",
"self",
",",
"len_",
")",
":",
"other",
"=",
"Version",
"(",
"None",
")",
"other",
".",
"tokens",
"=",
"self",
".",
"tokens",
"[",
":",
"len_",
"]",
"other",
".",
"seps",
"=",
"self",
".",
"seps",
"[",
":",
"len_",
"-",
"1",... | Return a copy of the version, possibly with less tokens.
Args:
len_ (int): New version length. If >= current length, an
unchanged copy of the version is returned. | [
"Return",
"a",
"copy",
"of",
"the",
"version",
"possibly",
"with",
"less",
"tokens",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L304-L314 | train | 227,578 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.union | def union(self, other):
"""OR together version ranges.
Calculates the union of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to OR with.
Returns:
New VersionRange object representing the union.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds[:]
for range in other:
bounds += range.bounds
bounds = self._union(bounds)
range = VersionRange(None)
range.bounds = bounds
return range | python | def union(self, other):
"""OR together version ranges.
Calculates the union of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to OR with.
Returns:
New VersionRange object representing the union.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds[:]
for range in other:
bounds += range.bounds
bounds = self._union(bounds)
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"__iter__\"",
")",
":",
"other",
"=",
"[",
"other",
"]",
"bounds",
"=",
"self",
".",
"bounds",
"[",
":",
"]",
"for",
"range",
"in",
"other",
":",
"b... | OR together version ranges.
Calculates the union of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to OR with.
Returns:
New VersionRange object representing the union. | [
"OR",
"together",
"version",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L814-L834 | train | 227,579 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.intersection | def intersection(self, other):
"""AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or None if
no ranges intersect.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds
for range in other:
bounds = self._intersection(bounds, range.bounds)
if not bounds:
return None
range = VersionRange(None)
range.bounds = bounds
return range | python | def intersection(self, other):
"""AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or None if
no ranges intersect.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds
for range in other:
bounds = self._intersection(bounds, range.bounds)
if not bounds:
return None
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"__iter__\"",
")",
":",
"other",
"=",
"[",
"other",
"]",
"bounds",
"=",
"self",
".",
"bounds",
"for",
"range",
"in",
"other",
":",
"bounds",
"=",... | AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or None if
no ranges intersect. | [
"AND",
"together",
"version",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L836-L859 | train | 227,580 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.inverse | def inverse(self):
"""Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range).
"""
if self.is_any():
return None
else:
bounds = self._inverse(self.bounds)
range = VersionRange(None)
range.bounds = bounds
return range | python | def inverse(self):
"""Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range).
"""
if self.is_any():
return None
else:
bounds = self._inverse(self.bounds)
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"inverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_any",
"(",
")",
":",
"return",
"None",
"else",
":",
"bounds",
"=",
"self",
".",
"_inverse",
"(",
"self",
".",
"bounds",
")",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".... | Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range). | [
"Calculate",
"the",
"inverse",
"of",
"the",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L861-L874 | train | 227,581 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.split | def split(self):
"""Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"].
"""
ranges = []
for bound in self.bounds:
range = VersionRange(None)
range.bounds = [bound]
ranges.append(range)
return ranges | python | def split(self):
"""Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"].
"""
ranges = []
for bound in self.bounds:
range = VersionRange(None)
range.bounds = [bound]
ranges.append(range)
return ranges | [
"def",
"split",
"(",
"self",
")",
":",
"ranges",
"=",
"[",
"]",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"bound",
"]",
"ranges",
".",
"append",
"(",
"range",... | Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"]. | [
"Split",
"into",
"separate",
"contiguous",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L887-L899 | train | 227,582 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.as_span | def as_span(cls, lower_version=None, upper_version=None,
lower_inclusive=True, upper_inclusive=True):
"""Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object representing upper bound of the range.
Returns:
`VersionRange` object.
"""
lower = (None if lower_version is None
else _LowerBound(lower_version, lower_inclusive))
upper = (None if upper_version is None
else _UpperBound(upper_version, upper_inclusive))
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | python | def as_span(cls, lower_version=None, upper_version=None,
lower_inclusive=True, upper_inclusive=True):
"""Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object representing upper bound of the range.
Returns:
`VersionRange` object.
"""
lower = (None if lower_version is None
else _LowerBound(lower_version, lower_inclusive))
upper = (None if upper_version is None
else _UpperBound(upper_version, upper_inclusive))
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | [
"def",
"as_span",
"(",
"cls",
",",
"lower_version",
"=",
"None",
",",
"upper_version",
"=",
"None",
",",
"lower_inclusive",
"=",
"True",
",",
"upper_inclusive",
"=",
"True",
")",
":",
"lower",
"=",
"(",
"None",
"if",
"lower_version",
"is",
"None",
"else",
... | Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object representing upper bound of the range.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"lower_version",
"..",
"upper_version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L902-L921 | train | 227,583 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.from_version | def from_version(cls, version, op=None):
"""Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object.
"""
lower = None
upper = None
if op is None:
lower = _LowerBound(version, True)
upper = _UpperBound(version.next(), False)
elif op in ("eq", "=="):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
elif op in ("gt", ">"):
lower = _LowerBound(version, False)
elif op in ("gte", ">="):
lower = _LowerBound(version, True)
elif op in ("lt", "<"):
upper = _UpperBound(version, False)
elif op in ("lte", "<="):
upper = _UpperBound(version, True)
else:
raise VersionError("Unknown bound operation '%s'" % op)
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | python | def from_version(cls, version, op=None):
"""Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object.
"""
lower = None
upper = None
if op is None:
lower = _LowerBound(version, True)
upper = _UpperBound(version.next(), False)
elif op in ("eq", "=="):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
elif op in ("gt", ">"):
lower = _LowerBound(version, False)
elif op in ("gte", ">="):
lower = _LowerBound(version, True)
elif op in ("lt", "<"):
upper = _UpperBound(version, False)
elif op in ("lte", "<="):
upper = _UpperBound(version, True)
else:
raise VersionError("Unknown bound operation '%s'" % op)
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | [
"def",
"from_version",
"(",
"cls",
",",
"version",
",",
"op",
"=",
"None",
")",
":",
"lower",
"=",
"None",
"upper",
"=",
"None",
"if",
"op",
"is",
"None",
":",
"lower",
"=",
"_LowerBound",
"(",
"version",
",",
"True",
")",
"upper",
"=",
"_UpperBound"... | Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"a",
"version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L924-L960 | train | 227,584 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.from_versions | def from_versions(cls, versions):
"""Create a range from a list of versions.
This method creates a range that contains only the given versions and
no other. Typically the range looks like (for eg) "==3|==4|==5.1".
Args:
versions: List of Version objects.
Returns:
`VersionRange` object.
"""
range = cls(None)
range.bounds = []
for version in dedup(sorted(versions)):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
bound = _Bound(lower, upper)
range.bounds.append(bound)
return range | python | def from_versions(cls, versions):
"""Create a range from a list of versions.
This method creates a range that contains only the given versions and
no other. Typically the range looks like (for eg) "==3|==4|==5.1".
Args:
versions: List of Version objects.
Returns:
`VersionRange` object.
"""
range = cls(None)
range.bounds = []
for version in dedup(sorted(versions)):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
bound = _Bound(lower, upper)
range.bounds.append(bound)
return range | [
"def",
"from_versions",
"(",
"cls",
",",
"versions",
")",
":",
"range",
"=",
"cls",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"]",
"for",
"version",
"in",
"dedup",
"(",
"sorted",
"(",
"versions",
")",
")",
":",
"lower",
"=",
"_LowerBound",
... | Create a range from a list of versions.
This method creates a range that contains only the given versions and
no other. Typically the range looks like (for eg) "==3|==4|==5.1".
Args:
versions: List of Version objects.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"a",
"list",
"of",
"versions",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L963-L982 | train | 227,585 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.to_versions | def to_versions(self):
"""Returns exact version ranges as Version objects, or None if there
are no exact version ranges present.
"""
versions = []
for bound in self.bounds:
if bound.lower.inclusive and bound.upper.inclusive \
and (bound.lower.version == bound.upper.version):
versions.append(bound.lower.version)
return versions or None | python | def to_versions(self):
"""Returns exact version ranges as Version objects, or None if there
are no exact version ranges present.
"""
versions = []
for bound in self.bounds:
if bound.lower.inclusive and bound.upper.inclusive \
and (bound.lower.version == bound.upper.version):
versions.append(bound.lower.version)
return versions or None | [
"def",
"to_versions",
"(",
"self",
")",
":",
"versions",
"=",
"[",
"]",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"if",
"bound",
".",
"lower",
".",
"inclusive",
"and",
"bound",
".",
"upper",
".",
"inclusive",
"and",
"(",
"bound",
".",
"lower"... | Returns exact version ranges as Version objects, or None if there
are no exact version ranges present. | [
"Returns",
"exact",
"version",
"ranges",
"as",
"Version",
"objects",
"or",
"None",
"if",
"there",
"are",
"no",
"exact",
"version",
"ranges",
"present",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L984-L994 | train | 227,586 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.contains_version | def contains_version(self, version):
"""Returns True if version is contained in this range."""
if len(self.bounds) < 5:
# not worth overhead of binary search
for bound in self.bounds:
i = bound.version_containment(version)
if i == 0:
return True
if i == -1:
return False
else:
_, contains = self._contains_version(version)
return contains
return False | python | def contains_version(self, version):
"""Returns True if version is contained in this range."""
if len(self.bounds) < 5:
# not worth overhead of binary search
for bound in self.bounds:
i = bound.version_containment(version)
if i == 0:
return True
if i == -1:
return False
else:
_, contains = self._contains_version(version)
return contains
return False | [
"def",
"contains_version",
"(",
"self",
",",
"version",
")",
":",
"if",
"len",
"(",
"self",
".",
"bounds",
")",
"<",
"5",
":",
"# not worth overhead of binary search",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"i",
"=",
"bound",
".",
"version_conta... | Returns True if version is contained in this range. | [
"Returns",
"True",
"if",
"version",
"is",
"contained",
"in",
"this",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L996-L1010 | train | 227,587 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.iter_intersecting | def iter_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_INTERSECTING) | python | def iter_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_INTERSECTING) | [
"def",
"iter_intersecting",
"(",
"self",
",",
"iterable",
",",
"key",
"=",
"None",
",",
"descending",
"=",
"False",
")",
":",
"return",
"_ContainsVersionIterator",
"(",
"self",
",",
"iterable",
",",
"key",
",",
"descending",
",",
"mode",
"=",
"_ContainsVersi... | Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect. | [
"Like",
"iter_intersect_test",
"but",
"returns",
"intersections",
"only",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1033-L1040 | train | 227,588 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.iter_non_intersecting | def iter_non_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_NON_INTERSECTING) | python | def iter_non_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_NON_INTERSECTING) | [
"def",
"iter_non_intersecting",
"(",
"self",
",",
"iterable",
",",
"key",
"=",
"None",
",",
"descending",
"=",
"False",
")",
":",
"return",
"_ContainsVersionIterator",
"(",
"self",
",",
"iterable",
",",
"key",
",",
"descending",
",",
"mode",
"=",
"_ContainsV... | Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect. | [
"Like",
"iter_intersect_test",
"but",
"returns",
"non",
"-",
"intersections",
"only",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1042-L1049 | train | 227,589 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.span | def span(self):
"""Return a contiguous range that is a superset of this range.
Returns:
A VersionRange object representing the span of this range. For
example, the span of "2+<4|6+<8" would be "2+<8".
"""
other = VersionRange(None)
bound = _Bound(self.bounds[0].lower, self.bounds[-1].upper)
other.bounds = [bound]
return other | python | def span(self):
"""Return a contiguous range that is a superset of this range.
Returns:
A VersionRange object representing the span of this range. For
example, the span of "2+<4|6+<8" would be "2+<8".
"""
other = VersionRange(None)
bound = _Bound(self.bounds[0].lower, self.bounds[-1].upper)
other.bounds = [bound]
return other | [
"def",
"span",
"(",
"self",
")",
":",
"other",
"=",
"VersionRange",
"(",
"None",
")",
"bound",
"=",
"_Bound",
"(",
"self",
".",
"bounds",
"[",
"0",
"]",
".",
"lower",
",",
"self",
".",
"bounds",
"[",
"-",
"1",
"]",
".",
"upper",
")",
"other",
"... | Return a contiguous range that is a superset of this range.
Returns:
A VersionRange object representing the span of this range. For
example, the span of "2+<4|6+<8" would be "2+<8". | [
"Return",
"a",
"contiguous",
"range",
"that",
"is",
"a",
"superset",
"of",
"this",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1051-L1061 | train | 227,590 |
nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.visit_versions | def visit_versions(self, func):
"""Visit each version in the range, and apply a function to each.
This is for advanced usage only.
If `func` returns a `Version`, this call will change the versions in
place.
It is possible to change versions in a way that is nonsensical - for
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place.
"""
for bound in self.bounds:
if bound.lower is not _LowerBound.min:
result = func(bound.lower.version)
if isinstance(result, Version):
bound.lower.version = result
if bound.upper is not _UpperBound.inf:
result = func(bound.upper.version)
if isinstance(result, Version):
bound.upper.version = result | python | def visit_versions(self, func):
"""Visit each version in the range, and apply a function to each.
This is for advanced usage only.
If `func` returns a `Version`, this call will change the versions in
place.
It is possible to change versions in a way that is nonsensical - for
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place.
"""
for bound in self.bounds:
if bound.lower is not _LowerBound.min:
result = func(bound.lower.version)
if isinstance(result, Version):
bound.lower.version = result
if bound.upper is not _UpperBound.inf:
result = func(bound.upper.version)
if isinstance(result, Version):
bound.upper.version = result | [
"def",
"visit_versions",
"(",
"self",
",",
"func",
")",
":",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"if",
"bound",
".",
"lower",
"is",
"not",
"_LowerBound",
".",
"min",
":",
"result",
"=",
"func",
"(",
"bound",
".",
"lower",
".",
"version"... | Visit each version in the range, and apply a function to each.
This is for advanced usage only.
If `func` returns a `Version`, this call will change the versions in
place.
It is possible to change versions in a way that is nonsensical - for
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place. | [
"Visit",
"each",
"version",
"in",
"the",
"range",
"and",
"apply",
"a",
"function",
"to",
"each",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1065-L1092 | train | 227,591 |
getsentry/raven-python | raven/transport/http.py | HTTPTransport.send | def send(self, url, data, headers):
"""
Sends a request to a remote webserver using HTTP POST.
"""
req = urllib2.Request(url, headers=headers)
try:
response = urlopen(
url=req,
data=data,
timeout=self.timeout,
verify_ssl=self.verify_ssl,
ca_certs=self.ca_certs,
)
except urllib2.HTTPError as exc:
msg = exc.headers.get('x-sentry-error')
code = exc.getcode()
if code == 429:
try:
retry_after = int(exc.headers.get('retry-after'))
except (ValueError, TypeError):
retry_after = 0
raise RateLimited(msg, retry_after)
elif msg:
raise APIError(msg, code)
else:
raise
return response | python | def send(self, url, data, headers):
"""
Sends a request to a remote webserver using HTTP POST.
"""
req = urllib2.Request(url, headers=headers)
try:
response = urlopen(
url=req,
data=data,
timeout=self.timeout,
verify_ssl=self.verify_ssl,
ca_certs=self.ca_certs,
)
except urllib2.HTTPError as exc:
msg = exc.headers.get('x-sentry-error')
code = exc.getcode()
if code == 429:
try:
retry_after = int(exc.headers.get('retry-after'))
except (ValueError, TypeError):
retry_after = 0
raise RateLimited(msg, retry_after)
elif msg:
raise APIError(msg, code)
else:
raise
return response | [
"def",
"send",
"(",
"self",
",",
"url",
",",
"data",
",",
"headers",
")",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"try",
":",
"response",
"=",
"urlopen",
"(",
"url",
"=",
"req",
",",
"data",
"=... | Sends a request to a remote webserver using HTTP POST. | [
"Sends",
"a",
"request",
"to",
"a",
"remote",
"webserver",
"using",
"HTTP",
"POST",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/http.py#L31-L58 | train | 227,592 |
getsentry/raven-python | raven/contrib/django/views.py | extract_auth_vars | def extract_auth_vars(request):
"""
raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations.
"""
if request.META.get('HTTP_X_SENTRY_AUTH', '').startswith('Sentry'):
return request.META['HTTP_X_SENTRY_AUTH']
elif request.META.get('HTTP_AUTHORIZATION', '').startswith('Sentry'):
return request.META['HTTP_AUTHORIZATION']
else:
# Try to construct from GET request
args = [
'%s=%s' % i
for i in request.GET.items()
if i[0].startswith('sentry_') and i[0] != 'sentry_data'
]
if args:
return 'Sentry %s' % ', '.join(args)
return None | python | def extract_auth_vars(request):
"""
raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations.
"""
if request.META.get('HTTP_X_SENTRY_AUTH', '').startswith('Sentry'):
return request.META['HTTP_X_SENTRY_AUTH']
elif request.META.get('HTTP_AUTHORIZATION', '').startswith('Sentry'):
return request.META['HTTP_AUTHORIZATION']
else:
# Try to construct from GET request
args = [
'%s=%s' % i
for i in request.GET.items()
if i[0].startswith('sentry_') and i[0] != 'sentry_data'
]
if args:
return 'Sentry %s' % ', '.join(args)
return None | [
"def",
"extract_auth_vars",
"(",
"request",
")",
":",
"if",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_SENTRY_AUTH'",
",",
"''",
")",
".",
"startswith",
"(",
"'Sentry'",
")",
":",
"return",
"request",
".",
"META",
"[",
"'HTTP_X_SENTRY_AUTH'",
"]",
"... | raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations. | [
"raven",
"-",
"js",
"will",
"pass",
"both",
"Authorization",
"and",
"X",
"-",
"Sentry",
"-",
"Auth",
"depending",
"on",
"the",
"browser",
"and",
"server",
"configurations",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/views.py#L61-L79 | train | 227,593 |
getsentry/raven-python | raven/events.py | Exception._get_value | def _get_value(self, exc_type, exc_value, exc_traceback):
"""
Convert exception info to a value for the values list.
"""
stack_info = get_stack_info(
iter_traceback_frames(exc_traceback),
transformer=self.transform,
capture_locals=self.client.capture_locals,
)
exc_module = getattr(exc_type, '__module__', None)
if exc_module:
exc_module = str(exc_module)
exc_type = getattr(exc_type, '__name__', '<unknown>')
return {
'value': to_unicode(exc_value),
'type': str(exc_type),
'module': to_unicode(exc_module),
'stacktrace': stack_info,
} | python | def _get_value(self, exc_type, exc_value, exc_traceback):
"""
Convert exception info to a value for the values list.
"""
stack_info = get_stack_info(
iter_traceback_frames(exc_traceback),
transformer=self.transform,
capture_locals=self.client.capture_locals,
)
exc_module = getattr(exc_type, '__module__', None)
if exc_module:
exc_module = str(exc_module)
exc_type = getattr(exc_type, '__name__', '<unknown>')
return {
'value': to_unicode(exc_value),
'type': str(exc_type),
'module': to_unicode(exc_module),
'stacktrace': stack_info,
} | [
"def",
"_get_value",
"(",
"self",
",",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
")",
":",
"stack_info",
"=",
"get_stack_info",
"(",
"iter_traceback_frames",
"(",
"exc_traceback",
")",
",",
"transformer",
"=",
"self",
".",
"transform",
",",
"capture_lo... | Convert exception info to a value for the values list. | [
"Convert",
"exception",
"info",
"to",
"a",
"value",
"for",
"the",
"values",
"list",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/events.py#L90-L110 | train | 227,594 |
getsentry/raven-python | raven/breadcrumbs.py | record | def record(message=None, timestamp=None, level=None, category=None,
data=None, type=None, processor=None):
"""Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client.
"""
if timestamp is None:
timestamp = time()
for ctx in raven.context.get_active_contexts():
ctx.breadcrumbs.record(timestamp, level, message, category,
data, type, processor) | python | def record(message=None, timestamp=None, level=None, category=None,
data=None, type=None, processor=None):
"""Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client.
"""
if timestamp is None:
timestamp = time()
for ctx in raven.context.get_active_contexts():
ctx.breadcrumbs.record(timestamp, level, message, category,
data, type, processor) | [
"def",
"record",
"(",
"message",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"level",
"=",
"None",
",",
"category",
"=",
"None",
",",
"data",
"=",
"None",
",",
"type",
"=",
"None",
",",
"processor",
"=",
"None",
")",
":",
"if",
"timestamp",
"i... | Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client. | [
"Records",
"a",
"breadcrumb",
"for",
"all",
"active",
"clients",
".",
"This",
"is",
"what",
"integration",
"code",
"should",
"use",
"rather",
"than",
"invoking",
"the",
"captureBreadcrumb",
"method",
"on",
"a",
"specific",
"client",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/breadcrumbs.py#L116-L126 | train | 227,595 |
getsentry/raven-python | raven/breadcrumbs.py | ignore_logger | def ignore_logger(name_or_logger, allow_level=None):
"""Ignores a logger during breadcrumb recording.
"""
def handler(logger, level, msg, args, kwargs):
if allow_level is not None and \
level >= allow_level:
return False
return True
register_special_log_handler(name_or_logger, handler) | python | def ignore_logger(name_or_logger, allow_level=None):
"""Ignores a logger during breadcrumb recording.
"""
def handler(logger, level, msg, args, kwargs):
if allow_level is not None and \
level >= allow_level:
return False
return True
register_special_log_handler(name_or_logger, handler) | [
"def",
"ignore_logger",
"(",
"name_or_logger",
",",
"allow_level",
"=",
"None",
")",
":",
"def",
"handler",
"(",
"logger",
",",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"allow_level",
"is",
"not",
"None",
"and",
"level",
">=",
"... | Ignores a logger during breadcrumb recording. | [
"Ignores",
"a",
"logger",
"during",
"breadcrumb",
"recording",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/breadcrumbs.py#L275-L283 | train | 227,596 |
getsentry/raven-python | raven/utils/serializer/manager.py | Serializer.transform | def transform(self, value, **kwargs):
"""
Primary function which handles recursively transforming
values via their serializers
"""
if value is None:
return None
objid = id(value)
if objid in self.context:
return '<...>'
self.context.add(objid)
try:
for serializer in self.serializers:
try:
if serializer.can(value):
return serializer.serialize(value, **kwargs)
except Exception as e:
logger.exception(e)
return text_type(type(value))
# if all else fails, lets use the repr of the object
try:
return repr(value)
except Exception as e:
logger.exception(e)
# It's common case that a model's __unicode__ definition
# may try to query the database which if it was not
# cleaned up correctly, would hit a transaction aborted
# exception
return text_type(type(value))
finally:
self.context.remove(objid) | python | def transform(self, value, **kwargs):
"""
Primary function which handles recursively transforming
values via their serializers
"""
if value is None:
return None
objid = id(value)
if objid in self.context:
return '<...>'
self.context.add(objid)
try:
for serializer in self.serializers:
try:
if serializer.can(value):
return serializer.serialize(value, **kwargs)
except Exception as e:
logger.exception(e)
return text_type(type(value))
# if all else fails, lets use the repr of the object
try:
return repr(value)
except Exception as e:
logger.exception(e)
# It's common case that a model's __unicode__ definition
# may try to query the database which if it was not
# cleaned up correctly, would hit a transaction aborted
# exception
return text_type(type(value))
finally:
self.context.remove(objid) | [
"def",
"transform",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"objid",
"=",
"id",
"(",
"value",
")",
"if",
"objid",
"in",
"self",
".",
"context",
":",
"return",
"'<...>'",
"sel... | Primary function which handles recursively transforming
values via their serializers | [
"Primary",
"function",
"which",
"handles",
"recursively",
"transforming",
"values",
"via",
"their",
"serializers"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/serializer/manager.py#L52-L85 | train | 227,597 |
getsentry/raven-python | raven/contrib/tornado/__init__.py | AsyncSentryClient.send | def send(self, auth_header=None, callback=None, **data):
"""
Serializes the message and passes the payload onto ``send_encoded``.
"""
message = self.encode(data)
return self.send_encoded(message, auth_header=auth_header, callback=callback) | python | def send(self, auth_header=None, callback=None, **data):
"""
Serializes the message and passes the payload onto ``send_encoded``.
"""
message = self.encode(data)
return self.send_encoded(message, auth_header=auth_header, callback=callback) | [
"def",
"send",
"(",
"self",
",",
"auth_header",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"data",
")",
":",
"message",
"=",
"self",
".",
"encode",
"(",
"data",
")",
"return",
"self",
".",
"send_encoded",
"(",
"message",
",",
"auth_hea... | Serializes the message and passes the payload onto ``send_encoded``. | [
"Serializes",
"the",
"message",
"and",
"passes",
"the",
"payload",
"onto",
"send_encoded",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L47-L53 | train | 227,598 |
getsentry/raven-python | raven/contrib/tornado/__init__.py | AsyncSentryClient._send_remote | def _send_remote(self, url, data, headers=None, callback=None):
"""
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
"""
if headers is None:
headers = {}
return AsyncHTTPClient().fetch(
url, callback, method="POST", body=data, headers=headers,
validate_cert=self.validate_cert
) | python | def _send_remote(self, url, data, headers=None, callback=None):
"""
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
"""
if headers is None:
headers = {}
return AsyncHTTPClient().fetch(
url, callback, method="POST", body=data, headers=headers,
validate_cert=self.validate_cert
) | [
"def",
"_send_remote",
"(",
"self",
",",
"url",
",",
"data",
",",
"headers",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"return",
"AsyncHTTPClient",
"(",
")",
".",
"fetch",
"(",
... | Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response. | [
"Initialise",
"a",
"Tornado",
"AsyncClient",
"and",
"send",
"the",
"request",
"to",
"the",
"sentry",
"server",
".",
"If",
"the",
"callback",
"is",
"a",
"callable",
"it",
"will",
"be",
"called",
"with",
"the",
"response",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L82-L94 | train | 227,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.