rez.resolved_context

class rez.resolved_context.PatchLock(value, names=None, module=None, type=None)[source]

Bases: rez.vendor.enum.Enum

Enum to represent the ‘lock type’ used when patching context objects.

class rez.resolved_context.ResolvedContext(package_requests, verbosity=0, timestamp=None, building=False, caching=None, package_paths=None, package_filter=None, package_orderers=None, max_fails=- 1, add_implicit_packages=True, time_limit=- 1, callback=None, package_load_callback=None, buf=None, suppress_passive=False, print_stats=False, package_caching=None)[source]

Bases: object

A class that resolves, stores and spawns Rez environments.

The main Rez entry point for creating, saving, loading and executing resolved environments. A ResolvedContext object can be saved to file and loaded at a later date, and it can reconstruct the equivalent environment at that time. It can spawn interactive and non-interactive shells, in any supported shell plugin type, such as bash and tcsh. It can also run a command within a configured python namespace, without spawning a child shell.

class Callback(max_fails, time_limit, callback, buf=None)[source]

Bases: object

apply(parent_environ=None)[source]

Apply the context to the current python session.

Note that this updates os.environ and possibly sys.path, if parent_environ is not provided.

Parameters

parent_environ – Environment to interpret the context within, defaults to os.environ if None.

context_tracking_lock = <unlocked _thread.lock object>
context_tracking_payload = None
copy()[source]

Returns a shallow copy of the context.

execute_command(args, parent_environ=None, **Popen_args)[source]

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.

Parameters
  • args – Command arguments, can be a string.

  • parent_environ – Environment to interpret the context within, defaults to os.environ if None.

  • Popen_args – Args to pass to subprocess.Popen.

Returns

A subprocess.Popen object.

Note

This does not alter the current python session.

execute_rex_code(code, filename=None, shell=None, parent_environ=None, **Popen_args)[source]

Run some rex code in the context.

Note

This is just a convenience form of execute_shell.

Parameters
  • 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.

execute_shell(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)[source]

Spawn a possibly-interactive shell.

Parameters
  • 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

A 3-tuple of (returncode, stdout, stderr); If non-blocking - A subprocess.Popen object for the shell process.

Return type

If blocking

classmethod from_dict(d, identifier_str=None)[source]

Load a ResolvedContext from a dict.

Parameters
  • d (dict) – Dict containing context data.

  • identifier_str (str) – String identifying the context, this is only used to display in an error string if a serialization version mismatch is detected.

Returns

ResolvedContext object.

get_actions(parent_environ=None)[source]

Get the list of rex.Action objects resulting from interpreting this context. This is provided mainly for testing purposes.

Parameters

within (parent_environ Environment to interpret the context) – defaults to os.environ if None.

:param : defaults to os.environ if None.

Returns

A list of rex.Action subclass instances.

get_conflicting_tools(request_only=False)[source]

Returns tools of the same name provided by more than one package.

Parameters

request_only – If True, only return the key from resolved packages that were also present in the request.

Returns

set([Variant])}.

Return type

Dict of {tool-name

classmethod get_current()[source]

Get the context for the current env, if there is one.

Returns

Current context, or None if not in a resolved env.

Return type

ResolvedContext

get_dependency_graph(as_dot=False)[source]

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.

get_environ(parent_environ=None)[source]

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_key(key, request_only=False)[source]

Get a data key value for each resolved package.

Parameters
  • 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

(variant, value)}.

Return type

Dict of {pkg-name

get_patched_request(package_requests=None, package_subtractions=None, strict=False, rank=0)[source]

Get a ‘patched’ request.

A patched request is a copy of this context’s request, but with some changes applied. This can then be used to create a new, ‘patched’ context.

New package requests override original requests based on the type - normal, conflict or weak. So ‘foo-2’ overrides ‘foo-1’, ‘!foo-2’ overrides ‘!foo-1’ and ‘~foo-2’ overrides ‘~foo-1’, but a request such as ‘!foo-2’ would not replace ‘foo-1’ - it would be added instead.

Note that requests in package_requests can have the form ‘^foo’. This is another way of supplying package subtractions.

Any new requests that don’t override original requests are appended, in the order that they appear in package_requests.

Parameters
  • package_requests (list of str or list of PackageRequest) – Overriding requests.

  • package_subtractions (list of str) – Any original request with a package name in this list is removed, before the new requests are added.

  • strict (bool) – If True, the current context’s resolve is used as the original request list, rather than the request.

  • rank (int) – If > 1, package versions can only increase in this rank and further - for example, rank=3 means that only version patch numbers are allowed to increase, major and minor versions will not change. This is only applied to packages that have not been explicitly overridden in package_requests. If rank <= 1, or strict is True, rank is ignored.

Returns

List of PackageRequest objects that can be used to construct a new ResolvedContext object.

get_resolve_as_exact_requests()[source]

Convert to a package request list of exact resolved package versions.

>>> r = ResolvedContext(['foo']
>>> r.get_resolve_as_exact_requests()
['foo==1.2.3', 'bah==1.0.1', 'python==2.7.12']
Returns

Context as a list of exact version requests.

Return type

List of PackageRequest

get_resolve_diff(other)[source]

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

  • ‘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.

Return type

A dict containing

get_resolved_package(name)[source]

Returns a Variant object or None if the package is not in the resolve.

get_shell_code(shell=None, parent_environ=None, style=<OutputStyle.file: ('Code as it would appear in a script file.', )>)[source]

Get the shell code resulting from intepreting this context.

Parameters
  • 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_tool_variants(tool_name)[source]

Get the variant(s) that provide the named tool.

If there are more than one variants, the tool is in conflict, and Rez does not know which variant’s tool is actually exposed.

Parameters

tool_name (str) – Name of the tool to search for.

Returns

Set of Variant objects. If no variant provides the tool, an empty set is returned.

get_tools(request_only=False)[source]

Returns the commandline tools available in the context.

Parameters

request_only – If True, only return the tools from resolved packages that were also present in the request.

Returns

(variant, [tools])}.

Return type

Dict of {pkg-name

graph(as_dot=False)[source]

Get the resolve graph.

Parameters

as_dot – If True, get the graph as a dot-language string. Otherwise, a pygraph.digraph object is returned.

Returns

A string or pygraph.digraph object, or None if there is no graph associated with the resolve.

property has_graph

Return True if the resolve has a graph.

is_current()[source]
Returns

True if this is the currently sourced context, False otherwise.

Return type

bool

classmethod load(path)[source]

Load a resolved context from file.

local = <_thread._local object>
package_cache_present = True
print_info(buf=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, verbosity=0, source_order=False, show_resolved_uris=False)[source]

Prints a message summarising the contents of the resolved context.

Parameters
  • buf (file-like object) – Where to print this info to.

  • verbosity (bool) – Verbose mode.

  • source_order (bool) – If True, print resolved packages in the order they are sourced, rather than alphabetical order.

  • show_resolved_uris (bool) – By default, resolved packages have their ‘root’ property listed, or their ‘uri’ if ‘root’ is None. Use this option to list ‘uri’ regardless.

print_resolve_diff(other, heading=None)[source]

Print the difference between the resolve of two contexts.

Parameters
  • 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_tools(buf=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]
classmethod read_from_buffer(buf, identifier_str=None)[source]

Load the context from a buffer.

requested_packages(include_implicit=False)[source]

Get packages in the request.

Parameters

include_implicit (bool) – If True, implicit packages are appended to the result.

Returns

List of PackageRequest objects.

property resolved_ephemerals

Get non-conflict ephemerals in the resolve.

Returns

List of Requirement objects, or None if the resolve failed.

property resolved_packages

Get packages in the resolve.

Returns

List of Variant objects, or None if the resolve failed.

retargeted(package_paths, package_names=None, skip_missing=False)[source]

Create a retargeted copy of this context.

Retargeting a context means replacing its variant references with the same variants from other package repositories.

Parameters
  • package_paths – List of paths to search for pkgs to retarget to.

  • package_names (list of str) – Only retarget these packages. If None, retarget all packages.

  • skip_missing (bool) – If True, skip retargeting of variants that cannot be found in package_paths. By default, a PackageNotFoundError is raised.

Returns

The retargeted context.

Return type

ResolvecContext`

save(path)[source]

Save the resolved context to file.

serialize_version = (4, 7)
set_load_path(path)[source]

Set the path that this context was reportedly loaded from.

You may want to use this method in cases where a context is saved to disk, but you need to associate this new path with the context while it is still in use.

property status

Return the current status of the context.

Returns

ResolverStatus.

property success

True if the context has been solved, False otherwise.

tmpdir_manager = <rez.utils.filesystem.TempDirs object>
to_dict(fields=None)[source]

Convert context to dict containing only builtin types.

Parameters

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

Dictified context.

Return type

dict

validate()[source]

Validate the context.

which(cmd, parent_environ=None, fallback=False)[source]

Find a program in the resolved environment.

Parameters
  • 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.

write_to_buffer(buf)[source]

Save the context to a buffer.

class rez.resolved_context.RezToolsVisibility(value, names=None, module=None, type=None)[source]

Bases: rez.vendor.enum.Enum

Determines if/how rez cli tools are added back to PATH within a resolved environment.

class rez.resolved_context.SuiteVisibility(value, names=None, module=None, type=None)[source]

Bases: rez.vendor.enum.Enum

Defines what suites on $PATH stay visible when a new rez environment is resolved.

rez.resolved_context.get_lock_request(name, version, patch_lock, weak=True)[source]

Given a package and patch lock, return the equivalent request.

For example, for object ‘foo-1.2.1’ and lock type ‘lock_3’, the equivalent request is ‘~foo-1.2’. This restricts updates to foo to patch-or-lower version changes only.

For objects not versioned down to a given lock level, the closest possible lock is applied. So ‘lock_3’ applied to ‘foo-1’ would give ‘~foo-1’.

Parameters
  • name (str) – Package name.

  • version (Version) – Package version.

  • patch_lock (PatchLock) – Lock type to apply.

Returns

PackageRequest object, or None if there is no equivalent request.