rez.resolved_context#

class rez.resolved_context.RezToolsVisibility#

Bases: Enum

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

never = 0#

Don’t expose rez in resolved env

append = 1#

Append to PATH in resolved env

prepend = 2#

Prepend to PATH in resolved env

class rez.resolved_context.SuiteVisibility#

Bases: Enum

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

never = 0#

Don’t attempt to keep any suites visible in a new env

always = 1#

Keep suites visible in any new env

parent = 2#

Keep only the parent suite of a tool visible

parent_priority = 3#

Keep all suites visible and the parent takes precedence

class rez.resolved_context.PatchLock#

Bases: Enum

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

no_lock = ('No locking', -1)#
lock_2 = ('Minor version updates only (X.*)', 1)#
lock_3 = ('Patch version updates only (X.X.*)', 2)#
lock_4 = ('Build version updates only (X.X.X.*)', 3)#
lock = ('Exact version', -1)#
rez.resolved_context.get_lock_request(name, version, patch_lock, weak=True)#

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

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

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

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.

Return type:

Optional[PackageRequest]

class rez.resolved_context.ResolvedContext#

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.

serialize_version = (4, 7)#
tmpdir_manager = <rez.utils.filesystem.TempDirs object>#
context_tracking_payload = None#
context_tracking_lock = <unlocked _thread.lock object>#
package_cache_present = True#
local = <_thread._local object>#
class Callback#

Bases: object

__init__(max_fails, time_limit, callback, buf=None)#
__init__(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)#

Perform a package resolve, and store the result.

Parameters:
  • package_requests (list[Union[str, PackageRequest]]) – request

  • verbosity (int) – Verbosity level. One of [0,1,2].

  • timestamp (float) – Ignore packages released after this epoch time. Packages released at exactly this time will not be ignored.

  • building (bool) – True if we’re resolving for a build.

  • caching (bool) – If True, cache(s) may be used to speed the resolve. If False, caches will not be used. If None, resolve_caching is used.

  • package_paths (list[str]) – List of paths to search for pkgs, defaults to packages_path.

  • package_filter (PackageFilterList) – Filter used to exclude certain packages. Defaults to settings from package_filter. Use rez.package_filter.no_filter to remove all filtering.

  • package_orderers (list[PackageOrder]) – Custom package ordering. Defaults to settings from package_orderers.

  • add_implicit_packages (bool) – If True, the implicit package list defined by implicit_packages is appended to the request.

  • max_fails (int) – Abort the resolve if the number of failed steps is greater or equal to this number. If -1, does not abort.

  • time_limit (int) – Abort the resolve if it takes longer than this many seconds. If -1, there is no time limit.

  • callback – See Solver.

  • package_load_callback – If not None, this callable will be called prior to each package being loaded. It is passed a single Package object.

  • buf (IO) – Where to print verbose output to, defaults to stdout.

  • suppress_passive (bool) – If True, don’t print debugging info that has had no effect on the solve. This argument only has an effect if verbosity > 2.

  • print_stats (bool) – If True, print advanced solver stats at the end.

  • package_caching (bool|None) – If True, apply package caching settings as per the config. If None, enable as determined by config setting package_cache_during_build.

property success#

True if the context has been solved, False otherwise.

property status#

Return the current status of the context.

Return type:

ResolverStatus

requested_packages(include_implicit=False)#

Get packages in the request.

Parameters:

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

Return type:

list[PackageRequest]

property resolved_packages#

Get packages in the resolve.

Returns:

Resolved variant objects, or None if the resolve failed.

Return type:

Optional[list[Variant]]

property resolved_ephemerals#

Get non-conflict ephemerals in the resolve.

Returns:

Requirement objects, or None if the resolve failed.

Return type:

Optional[list[Requirement]]

set_load_path(path)#

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 has_graph#

Return True if the resolve has a graph.

get_resolved_package(name)#

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

copy()#

Returns a shallow copy of the context.

retargeted(package_paths, package_names=None, skip_missing=False)#

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:

ResolvedContext

get_patched_request(package_requests=None, package_subtractions=None, strict=False, rank=0)#

Get a ‘patched’ request.

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

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

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

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

Parameters:
  • package_requests (list[Union[str, PackageRequest]) – Overriding requests.

  • package_subtractions (list[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:

PackageRequests objects that can be used to construct a new ResolvedContext object.

Return type:

list[PackageRequest]

graph(as_dot=False)#

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.

save(path)#

Save the resolved context to file.

write_to_buffer(buf)#

Save the context to a buffer.

classmethod get_current()#

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

is_current()#
Returns:

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

Return type:

bool

classmethod load(path)#

Load a resolved context from file.

classmethod read_from_buffer(buf, identifier_str=None)#

Load the context from a buffer.

get_resolve_diff(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.

Return type:

dict

print_info(buf=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, verbosity=0, source_order=False, show_resolved_uris=False)#

Prints a message summarising the contents of the resolved context.

Parameters:
  • buf (IO) – 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_tools(buf=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#
print_resolve_diff(other, heading=None)#

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.

get_dependency_graph(as_dot=False)#

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.

validate()#

Validate the context.

get_environ(parent_environ=None)#

Get the environ dict resulting from interpreting this context.

Parameters:

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)#

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:

Dict of {pkg-name: (variant, value)}.

get_tools(request_only=False)#

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:

Dict of {pkg-name: (variant, [tools])}.

get_tool_variants(tool_name)#

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_conflicting_tools(request_only=False)#

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:

Dict of {tool-name: set([Variant])}.

get_shell_code(shell=None, parent_environ=None, style=OutputStyle.file)#

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 (OutputStyle) – Style to format shell code in.

get_actions(parent_environ=None)#

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

Parameters:

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

Returns:

A list of rex.Action subclass instances.

apply(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.

Parameters:

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

which(cmd, parent_environ=None, fallback=False)#

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.

execute_command(args, parent_environ=None, **Popen_args)#

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)#

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 object for the shell process.

Return type:

subprocess.Popen

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)#

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:

If blocking, a 3-tuple of (returncode, stdout, stderr).

Note that if you want to get anything other than None for stdout and/or stderr, you need to give stdout=PIPE and/or stderr=PIPE.

If non-blocking, a subprocess.Popen object for the shell process.

get_resolve_as_exact_requests()#

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

to_dict(fields=None)#

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

classmethod from_dict(d, identifier_str=None)#

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.