Example #1
0
    def _print_context_info(self, value, buf=sys.stdout, b=False):
        word = "is also" if b else "is"
        _pr = Printer(buf)

        path = os.path.abspath(value)
        if not os.path.isfile(path):
            return False

        try:
            ResolvedContext.load(path)
        except:
            return False

        _pr("'%s' %s a context. Use 'rez-context' for more information." % (path, word))
        return True
Example #2
0
    def __init__(self, filepath):
        """Create a wrapper given its executable file."""
        from rez.suite import Suite

        def _err(msg):
            raise RezSystemError("Invalid executable file %s: %s" %
                                 (filepath, msg))

        with open(filepath) as f:
            content = f.read()
        try:
            doc = yaml.load(content, Loader=yaml.FullLoader)
            doc = doc["kwargs"]
            context_name = doc["context_name"]
            tool_name = doc["tool_name"]
            prefix_char = doc.get("prefix_char")
        except YAMLError as e:
            _err(str(e))

        # check that the suite is there - a wrapper may have been moved out of
        # a suite's ./bin path, which renders it useless.
        suite_path = os.path.dirname(os.path.dirname(filepath))
        try:
            Suite.load(suite_path)
        except SuiteError as e:
            _err(str(e))

        path = os.path.join(suite_path, "contexts", "%s.rxt" % context_name)
        context = ResolvedContext.load(path)
        self._init(suite_path, context_name, context, tool_name, prefix_char)
Example #3
0
File: wrapper.py Project: rvsiy/rez
    def __init__(self, filepath):
        """Create a wrapper given its executable file."""
        from rez.suite import Suite

        def _err(msg):
            raise RezSystemError("Invalid executable file %s: %s"
                                 % (filepath, msg))

        with open(filepath) as f:
            content = f.read()
        try:
            doc = yaml.load(content)
            doc = doc["kwargs"]
            context_name = doc["context_name"]
            tool_name = doc["tool_name"]
            prefix_char = doc.get("prefix_char")
        except YAMLError as e:
            _err(str(e))

        # check that the suite is there - a wrapper may have been moved out of
        # a suite's ./bin path, which renders it useless.
        suite_path = os.path.dirname(os.path.dirname(filepath))
        try:
            Suite.load(suite_path)
        except SuiteError as e:
            _err(str(e))

        path = os.path.join(suite_path, "contexts", "%s.rxt" % context_name)
        context = ResolvedContext.load(path)
        self._init(suite_path, context_name, context, tool_name, prefix_char)
Example #4
0
def application_parent_environment():
    import os
    from rez.resolved_context import ResolvedContext

    rxt = os.getenv("REZ_RXT_FILE")
    if not rxt:
        return os.environ.copy()

    # Allzpark is launched from a Rez resolved context, need to compute the
    # original environment so the application can be launched in a proper
    # parent environment.

    # TODO: Load environment from "house" package (.env file)

    context = ResolvedContext.load(rxt)
    context.append_sys_path = False
    changes = context.get_environ()
    current = os.environ.copy()
    rollbacked = dict()

    for key, value in current.items():
        current_paths = value.split(os.pathsep)
        changed_paths = changes.get(key, "").split(os.pathsep)
        roll_paths = []
        for path in current_paths:
            if path and path not in changed_paths:
                roll_paths.append(path)

        if roll_paths:
            rollbacked[key] = os.pathsep.join(roll_paths)

    return rollbacked
Example #5
0
def _FWD__spawn_build_shell(working_dir,
                            build_path,
                            variant_index,
                            install,
                            install_path=None):
    # This spawns a shell that the user can run the build command in directly
    context = ResolvedContext.load(os.path.join(build_path, "build.rxt"))
    package = get_developer_package(working_dir)
    variant = package.get_variant(variant_index)
    config.override("prompt", "BUILD>")

    actions_callback = functools.partial(CustomBuildSystem._add_build_actions,
                                         context=context,
                                         package=package,
                                         variant=variant,
                                         build_type=BuildType.local,
                                         install=install,
                                         build_path=build_path,
                                         install_path=install_path)

    post_actions_callback = functools.partial(
        CustomBuildSystem.add_pre_build_commands,
        variant=variant,
        build_type=BuildType.local,
        install=install,
        build_path=build_path,
        install_path=install_path)

    retcode, _, _ = context.execute_shell(
        block=True,
        cwd=build_path,
        actions_callback=actions_callback,
        post_actions_callback=post_actions_callback)

    sys.exit(retcode)
Example #6
0
def _FWD__spawn_build_shell(working_dir, build_dir):
    # This spawns a shell that the user can run 'bez' in directly
    context = ResolvedContext.load(os.path.join(build_dir, "build.rxt"))
    config.override("prompt", "BUILD>")

    retcode, _, _ = context.execute_shell(block=True, cwd=build_dir)
    sys.exit(retcode)
Example #7
0
    def context(self):
        """Get the current context.

        Returns:
            `ResolvedContext` or None if not in a context.
        """
        path = self.context_file
        return ResolvedContext.load(path) if path else None
Example #8
0
    def context(self):
        """Get the current context.

        Returns:
            `ResolvedContext` or None if not in a context.
        """
        path = self.context_file
        return ResolvedContext.load(path) if path else None
Example #9
0
 def test_serialize(self):
     """Test save/load of context."""
     # save
     file = os.path.join(self.root, "test.rxt")
     r = ResolvedContext(["hello_world"])
     r.save(file)
     # load
     r2 = ResolvedContext.load(file)
     self.assertEqual(r.resolved_packages, r2.resolved_packages)
Example #10
0
 def test_serialize(self):
     """Test save/load of context."""
     # save
     file = os.path.join(self.root, "test.rxt")
     r = ResolvedContext(["hello_world"])
     r.save(file)
     # load
     r2 = ResolvedContext.load(file)
     self.assertEqual(r.resolved_packages, r2.resolved_packages)
Example #11
0
def _FWD__invoke_suite_tool_alias(context_name, tool_name, _script, _cli_args):
    suite_path = os.path.dirname(os.path.dirname(_script))
    path = os.path.join(suite_path, "contexts", "%s.rxt" % context_name)
    context = ResolvedContext.load(path)

    from rez.wrapper import Wrapper
    w = Wrapper.__new__(Wrapper)
    w._init(suite_path, context_name, context, tool_name)
    retcode = w.run(*_cli_args)
    sys.exit(retcode)
Example #12
0
def action_resolve(requests_or_rxt):
    from rez.resolved_context import ResolvedContext  # noqa

    if os.path.isfile(requests_or_rxt):
        context = ResolvedContext.load(requests_or_rxt)
    else:
        context = ResolvedContext(requests_or_rxt.split(" "))

    resolved_env = context.get_environ()
    resolved_env_str = json.dumps(resolved_env)
    _flush(resolved_env_str)
Example #13
0
def _FWD__invoke_suite_tool_alias(context_name, tool_name, prefix_char=None, _script=None, _cli_args=None):
    suite_path = os.path.dirname(os.path.dirname(_script))
    path = os.path.join(suite_path, "contexts", "%s.rxt" % context_name)
    context = ResolvedContext.load(path)

    from rez.wrapper import Wrapper

    w = Wrapper.__new__(Wrapper)
    w._init(suite_path, context_name, context, tool_name, prefix_char)
    retcode = w.run(*(_cli_args or []))
    sys.exit(retcode)
Example #14
0
        def _test_bundle(path):
            # load the bundled context
            r2 = ResolvedContext.load(os.path.join(path, "context.rxt"))

            # check the pkg we contain is in the bundled pkg repo
            variant = r2.resolved_packages[0]
            self.assertTrue(
                is_subdirectory(variant.root, path),
                "Expected variant root %r of variant %r to be a subdirectory of %r"
                % (variant.root, variant.uri, path))

            self._test_execute_command_environ(r2)
Example #15
0
    def test_serialize(self):
        """Test context serialization."""

        # save
        file = os.path.join(self.root, "test.rxt")
        r = ResolvedContext(["hello_world"])
        r.save(file)

        # load
        r2 = ResolvedContext.load(file)
        self.assertEqual(r.resolved_packages, r2.resolved_packages)

        # verify
        env = r2.get_environ()
        self.assertEqual(env.get("OH_HAI_WORLD"), "hello")
Example #16
0
File: cmake.py Project: cb109/rez
def _FWD__spawn_build_shell(working_dir, build_dir, variant_index):
    # This spawns a shell that the user can run 'make' in directly
    context = ResolvedContext.load(os.path.join(build_dir, "build.rxt"))
    package = get_developer_package(working_dir)
    variant = package.get_variant(variant_index)
    config.override("prompt", "BUILD>")

    callback = functools.partial(CMakeBuildSystem._add_build_actions,
                                 context=context,
                                 package=package,
                                 variant=variant,
                                 build_type=BuildType.local)

    retcode, _, _ = context.execute_shell(block=True,
                                          cwd=build_dir,
                                          actions_callback=callback)
    sys.exit(retcode)
Example #17
0
File: suite.py Project: wwfxuk/rez
def _FWD__invoke_suite_tool_alias(context_name,
                                  tool_name,
                                  prefix_char=None,
                                  re_resolve=False,
                                  _script=None,
                                  _cli_args=None):
    suite_path = os.path.dirname(os.path.dirname(_script))
    path = os.path.join(suite_path, "contexts", "%s.rxt" % context_name)
    context = ResolvedContext.load(path)
    if re_resolve:
        context = context.re_resolved(context)

    from rez.wrapper import Wrapper
    w = Wrapper.__new__(Wrapper)
    w._init(suite_path, context_name, context, tool_name, prefix_char)
    retcode = w.run(*(_cli_args or []))
    sys.exit(retcode)
Example #18
0
File: cmake.py Project: mwiebe/rez
def _FWD__spawn_build_shell(working_dir, build_dir, variant_index):
    # This spawns a shell that the user can run 'make' in directly
    context = ResolvedContext.load(os.path.join(build_dir, "build.rxt"))
    package = get_developer_package(working_dir)
    variant = package.get_variant(variant_index)
    config.override("prompt", "BUILD>")

    callback = functools.partial(CMakeBuildSystem._add_build_actions,
                                 context=context,
                                 package=package,
                                 variant=variant,
                                 build_type=BuildType.local)

    retcode, _, _ = context.execute_shell(block=True,
                                          cwd=build_dir,
                                          actions_callback=callback)
    sys.exit(retcode)
Example #19
0
    def load_context(self, filepath):
        context = None
        busy_cursor = QtGui.QCursor(QtCore.Qt.WaitCursor)

        with self.status("Loading %s..." % filepath):
            QtGui.QApplication.setOverrideCursor(busy_cursor)
            try:
                context = ResolvedContext.load(filepath)
            except ResolvedContextError as e:
                QtGui.QMessageBox.critical(self.main_window,
                                           "Failed to load context", str(e))
            finally:
                QtGui.QApplication.restoreOverrideCursor()

        if context:
            path = os.path.realpath(filepath)
            self.config.prepend_string_list("most_recent_contexts", path,
                                            "max_most_recent_contexts")
        return context
Example #20
0
    def load_context(self, filepath):
        context = None
        busy_cursor = QtGui.QCursor(QtCore.Qt.WaitCursor)

        with self.status("Loading %s..." % filepath):
            QtGui.QApplication.setOverrideCursor(busy_cursor)
            try:
                context = ResolvedContext.load(filepath)
            except ResolvedContextError as e:
                QtGui.QMessageBox.critical(self.main_window,
                                           "Failed to load context", str(e))
            finally:
                QtGui.QApplication.restoreOverrideCursor()

        if context:
            path = os.path.realpath(filepath)
            self.config.prepend_string_list("most_recent_contexts", path,
                                            "max_most_recent_contexts")
        return context
Example #21
0
    def context(self, name):
        """Get a context.

        Args:
            name (str): Name to store the context under.

        Returns:
            `ResolvedContext` object.
        """
        data = self._context(name)
        context = data.get("context")
        if context:
            return context

        assert self.load_path
        context_path = os.path.join(self.load_path, "contexts", "%s.rxt" % name)
        context = ResolvedContext.load(context_path)
        data["context"] = context
        data["loaded"] = True
        return context
Example #22
0
    def context(self, name):
        """Get a context.

        Args:
            name (str): Name to store the context under.

        Returns:
            `ResolvedContext` object.
        """
        data = self._context(name)
        context = data.get("context")
        if context:
            return context

        assert self.load_path
        context_path = os.path.join(self.load_path, "contexts", "%s.rxt" % name)
        context = ResolvedContext.load(context_path)
        data["context"] = context
        data["loaded"] = True
        return context
Example #23
0
def command(opts, parser, extra_arg_groups=None):
    from rez.utils.logging_ import print_error
    from rez.bundle_context import bundle_context
    from rez.resolved_context import ResolvedContext

    rxt_filepath = os.path.abspath(os.path.expanduser(opts.RXT))
    dest_dir = os.path.abspath(os.path.expanduser(opts.DEST_DIR))

    # sanity checks
    if not os.path.exists(rxt_filepath):
        print_error("File does not exist: %s", rxt_filepath)
        sys.exit(1)

    context = ResolvedContext.load(rxt_filepath)

    bundle_context(context=context,
                   dest_dir=dest_dir,
                   force=opts.force,
                   skip_non_relocatable=opts.skip_non_relocatable,
                   verbose=opts.verbose)
Example #24
0
def get_tools(db_root, ctx, pkg, timestamp):
    """
    Given the appropriate information, list the tools available.

    Args:
        db_root (str): Path to the root of the database.
        ctx (str): The context.
        pkg (str): The package.
        timestamp (int): The timestamp in seconds since Jan 1, 1970

    Returns:
        generator of iterator over tools

    Raises:
        KeyError, RuntimeError
    """
    db_reader = reader.RezRxtDbReader(db_root)

    rxt_f = db_reader.resolve(ctx, pkg, timestamp, approximate=True)
    resolved = ResolvedContext.load(rxt_f)

    return resolved.get_tools().iteritems()
Example #25
0
def command(opts, parser, extra_arg_groups=None):
    from rez.status import status
    from rez.utils.formatting import columnise, PackageRequest
    from rez.resolved_context import ResolvedContext
    from rez.utils.graph_utils import save_graph, view_graph, prune_graph
    from pprint import pformat

    rxt_file = opts.RXT if opts.RXT else status.context_file
    if not rxt_file:
        print >> sys.stderr, "not in a resolved environment context."
        sys.exit(1)

    if rxt_file == '-':  # read from stdin
        rc = ResolvedContext.read_from_buffer(sys.stdin, 'STDIN')
    else:
        rc = ResolvedContext.load(rxt_file)

    def _graph():
        if rc.has_graph:
            return rc.graph(as_dot=True)
        else:
            print >> sys.stderr, "The context does not contain a graph."
            sys.exit(1)

    parent_env = {} if opts.no_env else None

    if not opts.interpret:
        if opts.print_request:
            print " ".join(str(x) for x in rc.requested_packages(False))
        elif opts.print_resolve:
            print ' '.join(x.qualified_package_name
                           for x in rc.resolved_packages)
        elif opts.tools:
            rc.print_tools()
        elif opts.diff:
            rc_other = ResolvedContext.load(opts.diff)
            rc.print_resolve_diff(rc_other, True)
        elif opts.fetch:
            rc_new = ResolvedContext(rc.requested_packages(),
                                     package_paths=rc.package_paths,
                                     verbosity=opts.verbose)
            rc.print_resolve_diff(rc_new, heading=("current", "updated"))
        elif opts.which:
            cmd = opts.which
            path = rc.which(cmd, parent_environ=parent_env)
            if path:
                print path
            else:
                print >> sys.stderr, "'%s' not found in the context" % cmd
        elif opts.print_graph:
            gstr = _graph()
            print gstr
        elif opts.graph or opts.write_graph:
            gstr = _graph()
            if opts.prune_pkg:
                req = PackageRequest(opts.prune_pkg)
                gstr = prune_graph(gstr, req.name)
            func = view_graph if opts.graph else save_graph
            func(gstr, dest_file=opts.write_graph)
        else:
            rc.print_info(verbosity=opts.verbose,
                          source_order=opts.source_order,
                          show_resolved_uris=opts.show_uris)
        return

    if opts.format in ("dict", "table", "json"):
        env = rc.get_environ(parent_environ=parent_env)

        if opts.format == 'table':
            rows = [x for x in sorted(env.iteritems())]
            print '\n'.join(columnise(rows))
        elif opts.format == 'dict':
            print pformat(env)
        else:  # json
            print json.dumps(env, sort_keys=True, indent=4)
    else:
        code = rc.get_shell_code(shell=opts.format,
                                 parent_environ=parent_env,
                                 style=OutputStyle[opts.style])
        print code
Example #26
0
def command(opts, parser, extra_arg_groups=None):
    from rez.suite import Suite
    from rez.status import status
    from rez.exceptions import SuiteError
    from rez.resolved_context import ResolvedContext
    import sys

    context_needed = set(("add", "prefix", "suffix", "hide", "unhide", "alias",
                          "unalias", "interactive"))
    save_needed = set(("add", "remove", "bump", "prefix", "suffix", "hide",
                       "unhide", "alias", "unalias"))

    def _pr(s):
        if opts.verbose:
            print s

    def _option(name):
        value = getattr(opts, name)
        if value and name in context_needed and not opts.context:
            parser.error("--context must be supplied when using --%s" %
                         name.replace('_', '-'))
        return value

    if opts.list:
        suites = status.suites
        if suites:
            for suite in suites:
                print suite.load_path
        else:
            print "No visible suites."
        sys.exit(0)

    if not opts.DIR:
        parser.error("DIR required.")

    if opts.create:
        suite = Suite()
        _pr("create empty suite at %r..." % opts.DIR)
        suite.save(opts.DIR)  # raises if dir already exists
        sys.exit(0)

    suite = Suite.load(opts.DIR)

    if _option("interactive"):
        context = suite.context(opts.context)
        retcode, _, _ = context.execute_shell(block=True)
        sys.exit(retcode)
    elif _option("validate"):
        try:
            suite.validate()
        except SuiteError as e:
            print >> sys.stderr, "The suite is invalid:\n%s" % str(e)
            sys.exit(1)
        print "The suite is valid."
    elif _option("find_request") or _option("find_resolve"):
        context_names = suite.find_contexts(in_request=opts.find_request,
                                            in_resolve=opts.find_resolve)
        if context_names:
            print '\n'.join(context_names)
    elif _option("print_tools"):
        suite.print_tools(verbose=opts.verbose, context_name=opts.context)
    elif _option("add"):
        _pr("loading context at %r..." % opts.add)
        context = ResolvedContext.load(opts.add)
        _pr("adding context %r..." % opts.context)
        suite.add_context(name=opts.context, context=context)
    elif _option("remove"):
        _pr("removing context %r..." % opts.remove)
        suite.remove_context(name=opts.remove)
    elif _option("bump"):
        _pr("bumping context %r..." % opts.bump)
        suite.bump_context(name=opts.bump)
    elif _option("prefix"):
        _pr("prefixing context %r..." % opts.context)
        suite.set_context_prefix(name=opts.context, prefix=opts.prefix)
    elif _option("suffix"):
        _pr("suffixing context %r..." % opts.context)
        suite.set_context_suffix(name=opts.context, suffix=opts.suffix)
    elif _option("hide"):
        _pr("hiding tool %r in context %r..." % (opts.hide, opts.context))
        suite.hide_tool(context_name=opts.context, tool_name=opts.hide)
    elif _option("unhide"):
        _pr("unhiding tool %r in context %r..." % (opts.unhide, opts.context))
        suite.unhide_tool(context_name=opts.context, tool_name=opts.unhide)
    elif _option("alias"):
        _pr("aliasing tool %r as %r in context %r..." %
            (opts.alias[0], opts.alias[1], opts.context))
        suite.alias_tool(context_name=opts.context,
                         tool_name=opts.alias[0],
                         tool_alias=opts.alias[1])
    elif _option("unalias"):
        _pr("unaliasing tool %r in context %r..." %
            (opts.unalias, opts.context))
        suite.unalias_tool(context_name=opts.context, tool_name=opts.unalias)
    elif _option("which"):
        filepath = suite.get_tool_filepath(opts.which)
        if filepath:
            print filepath
            sys.exit(0)
        else:
            sys.exit(1)
    elif opts.context:
        context = suite.context(opts.context)
        context.print_info(verbosity=opts.verbose)
    else:
        suite.print_info(verbose=opts.verbose)
        sys.exit(0)

    do_save = any(getattr(opts, x) for x in save_needed)
    if do_save:
        _pr("saving suite to %r..." % opts.DIR)
        suite.save(opts.DIR)
Example #27
0
def command(opts, parser, extra_arg_groups=None):
    from rez.resolved_context import ResolvedContext
    from rez.resolver import ResolverStatus
    from rez.package_filter import PackageFilterList, Rule
    from rez.utils.formatting import get_epoch_time_from_str
    from rez.config import config
    import select
    import sys
    import os
    import os.path

    command = opts.command
    if extra_arg_groups:
        if opts.command:
            parser.error("argument --command: not allowed with arguments after '--'")
        command = extra_arg_groups[0] or None

    context = None
    request = opts.PKG
    t = get_epoch_time_from_str(opts.time) if opts.time else None

    if opts.isolated:
        config.inherit_parent_environment = False

    if opts.inherited:
        config.inherit_parent_environment = True

    if opts.paths is None:
        pkg_paths = (config.nonlocal_packages_path
                     if opts.no_local else None)
    else:
        pkg_paths = opts.paths.split(os.pathsep)
        pkg_paths = [os.path.expanduser(x) for x in pkg_paths if x]

    if opts.input:
        if opts.PKG and not opts.patch:
            parser.error("Cannot use --input and provide PKG(s), unless patching.")

        context = ResolvedContext.load(opts.input)

    if opts.patch:
        if context is None:
            from rez.status import status
            context = status.context
            if context is None:
                print("cannot patch: not in a context", file=sys.stderr)
                sys.exit(1)

        # modify the request in terms of the given patch request
        request = context.get_patched_request(request,
                                              strict=opts.strict,
                                              rank=opts.patch_rank)
        context = None

    if opts.self:
        from rez.utils._version import _rez_version
        request += ["bleeding_rez==%s" % _rez_version]
        request += ["python"]  # Required by Rez

    if context is None:
        # create package filters
        if opts.no_filters:
            package_filter = PackageFilterList()
        else:
            package_filter = PackageFilterList.singleton.copy()

        for rule_str in (opts.exclude or []):
            rule = Rule.parse_rule(rule_str)
            package_filter.add_exclusion(rule)

        for rule_str in (opts.include or []):
            rule = Rule.parse_rule(rule_str)
            package_filter.add_inclusion(rule)

        # perform the resolve
        context = ResolvedContext(package_requests=request,
                                  timestamp=t,
                                  package_paths=pkg_paths,
                                  building=opts.build,
                                  package_filter=package_filter,
                                  add_implicit_packages=(not opts.no_implicit),
                                  verbosity=opts.verbose,
                                  max_fails=opts.max_fails,
                                  time_limit=opts.time_limit,
                                  caching=(not opts.no_cache),
                                  suppress_passive=opts.no_passive,
                                  print_stats=opts.stats)

    success = (context.status == ResolverStatus.solved)

    if not success:
        context.print_info(buf=sys.stderr)
        if opts.fail_graph:
            if context.graph:
                from rez.utils.graph_utils import view_graph
                g = context.graph(as_dot=True)
                view_graph(g)
            else:
                print("the failed resolve context did not generate a graph.", file=sys.stderr)

    if opts.output:
        if opts.output == '-':  # print to stdout
            context.write_to_buffer(sys.stdout)
        else:
            context.save(opts.output)
        sys.exit(0 if success else 1)

    if not success:
        sys.exit(1)

    if opts.env:
        env = {}

        for pair in opts.env:
            key, value = pair.split("=")
            env[key.upper()] = value

        config.additional_environment = env

    # generally shells will behave as though the '-s' flag was not present when
    # no stdin is available. So here we replicate this behaviour.
    try:
        if opts.stdin and not select.select([sys.stdin], [], [], 0.0)[0]:
            opts.stdin = False
    except select.error:
        pass  # because windows

    quiet = opts.quiet or bool(command)
    returncode, _, _ = context.execute_shell(
        shell=opts.shell,
        rcfile=opts.rcfile,
        norc=opts.norc,
        command=command,
        stdin=opts.stdin,
        quiet=quiet,
        start_new_session=opts.new_session,
        detached=opts.detached,
        pre_command=opts.pre_command,
        block=True)

    sys.exit(returncode)
Example #28
0
def command(opts, parser, extra_arg_groups=None):
    from rez.resolved_context import ResolvedContext
    from rez.resolver import ResolverStatus
    from rez.package_filter import PackageFilterList, Rule
    from rez.utils.formatting import get_epoch_time_from_str
    from rez.config import config
    import select
    import sys
    import os
    import os.path

    command = opts.command
    if extra_arg_groups:
        if opts.command:
            parser.error("argument --command: not allowed with arguments after '--'")
        command = extra_arg_groups[0] or None

    context = None
    request = opts.PKG
    t = get_epoch_time_from_str(opts.time) if opts.time else None

    if opts.paths is None:
        pkg_paths = (config.nonlocal_packages_path
                     if opts.no_local else None)
    else:
        pkg_paths = opts.paths.split(os.pathsep)
        pkg_paths = [os.path.expanduser(x) for x in pkg_paths if x]

    if opts.input:
        if opts.PKG and not opts.patch:
            parser.error("Cannot use --input and provide PKG(s), unless patching.")

        context = ResolvedContext.load(opts.input)

    if opts.patch:
        if context is None:
            from rez.status import status
            context = status.context
            if context is None:
                print >> sys.stderr, "cannot patch: not in a context"
                sys.exit(1)

        # modify the request in terms of the given patch request
        request = context.get_patched_request(request,
                                              strict=opts.strict,
                                              rank=opts.patch_rank)
        context = None

    if context is None:
        # create package filters
        if opts.no_filters:
            package_filter = PackageFilterList()
        else:
            package_filter = PackageFilterList.singleton.copy()

        for rule_str in (opts.exclude or []):
            rule = Rule.parse_rule(rule_str)
            package_filter.add_exclusion(rule)

        for rule_str in (opts.include or []):
            rule = Rule.parse_rule(rule_str)
            package_filter.add_inclusion(rule)

        # perform the resolve
        context = ResolvedContext(package_requests=request,
                                  timestamp=t,
                                  package_paths=pkg_paths,
                                  building=opts.build,
                                  package_filter=package_filter,
                                  add_implicit_packages=(not opts.no_implicit),
                                  verbosity=opts.verbose,
                                  max_fails=opts.max_fails,
                                  time_limit=opts.time_limit,
                                  caching=(not opts.no_cache),
                                  suppress_passive=opts.no_passive,
                                  print_stats=opts.stats)

    success = (context.status == ResolverStatus.solved)

    if not success:
        context.print_info(buf=sys.stderr)
        if opts.fail_graph:
            if context.graph:
                from rez.utils.graph_utils import view_graph
                g = context.graph(as_dot=True)
                view_graph(g)
            else:
                print >> sys.stderr, \
                    "the failed resolve context did not generate a graph."

    if opts.output:
        if opts.output == '-':  # print to stdout
            context.write_to_buffer(sys.stdout)
        else:
            context.save(opts.output)
        sys.exit(0 if success else 1)

    if not success:
        sys.exit(1)

    # generally shells will behave as though the '-s' flag was not present when
    # no stdin is available. So here we replicate this behaviour.
    try:
        if opts.stdin and not select.select([sys.stdin], [], [], 0.0)[0]:
            opts.stdin = False
    except select.error:
        pass  # because windows

    quiet = opts.quiet or bool(command)
    returncode, _, _ = context.execute_shell(
        shell=opts.shell,
        rcfile=opts.rcfile,
        norc=opts.norc,
        command=command,
        stdin=opts.stdin,
        quiet=quiet,
        start_new_session=opts.new_session,
        detached=opts.detached,
        pre_command=opts.pre_command,
        block=True)

    sys.exit(returncode)
Example #29
0
File: context.py Project: rvsiy/rez
def command(opts, parser, extra_arg_groups=None):
    from rez.status import status
    from rez.utils.formatting import columnise, PackageRequest
    from rez.resolved_context import ResolvedContext
    from rez.utils.graph_utils import save_graph, view_graph, prune_graph
    from pprint import pformat

    rxt_file = opts.RXT if opts.RXT else status.context_file
    if not rxt_file:
        print >> sys.stderr, "not in a resolved environment context."
        sys.exit(1)

    if rxt_file == '-':  # read from stdin
        rc = ResolvedContext.read_from_buffer(sys.stdin, 'STDIN')
    else:
        rc = ResolvedContext.load(rxt_file)

    def _graph():
        if rc.has_graph:
            return rc.graph(as_dot=True)
        else:
            print >> sys.stderr, "The context does not contain a graph."
            sys.exit(1)

    parent_env = {} if opts.no_env else None

    if not opts.interpret:
        if opts.print_request:
            print " ".join(str(x) for x in rc.requested_packages(False))
        elif opts.print_resolve:
            print ' '.join(x.qualified_package_name for x in rc.resolved_packages)
        elif opts.tools:
            rc.print_tools()
        elif opts.diff:
            rc_other = ResolvedContext.load(opts.diff)
            rc.print_resolve_diff(rc_other, True)
        elif opts.fetch:
            rc_new = ResolvedContext(rc.requested_packages(),
                                     package_paths=rc.package_paths,
                                     verbosity=opts.verbose)
            rc.print_resolve_diff(rc_new, heading=("current", "updated"))
        elif opts.which:
            cmd = opts.which
            path = rc.which(cmd, parent_environ=parent_env)
            if path:
                print path
            else:
                print >> sys.stderr, "'%s' not found in the context" % cmd
        elif opts.print_graph:
            gstr = _graph()
            print gstr
        elif opts.graph or opts.write_graph:
            gstr = _graph()
            if opts.prune_pkg:
                req = PackageRequest(opts.prune_pkg)
                gstr = prune_graph(gstr, req.name)
            func = view_graph if opts.graph else save_graph
            func(gstr, dest_file=opts.write_graph)
        else:
            rc.print_info(verbosity=opts.verbose,
                          source_order=opts.source_order,
                          show_resolved_uris=opts.show_uris)
        return

    if opts.format == 'table':
        env = rc.get_environ(parent_environ=parent_env)
        rows = [x for x in sorted(env.iteritems())]
        print '\n'.join(columnise(rows))
    elif opts.format == 'dict':
        env = rc.get_environ(parent_environ=parent_env)
        print pformat(env)
    else:
        code = rc.get_shell_code(shell=opts.format,
                                 parent_environ=parent_env,
                                 style=OutputStyle[opts.style])
        print code
Example #30
0
def command(opts, parser, extra_arg_groups=None):
    from rez.resolved_context import ResolvedContext
    from rez.resolver import ResolverStatus
    from rez.package_filter import PackageFilterList, Rule
    from rez.utils.formatting import get_epoch_time_from_str
    from rez.config import config
    import select
    import sys
    import os
    import os.path

    command = opts.command
    if extra_arg_groups:
        if opts.command:
            parser.error(
                "argument --command: not allowed with arguments after '--'")
        command = extra_arg_groups[0] or None

    context = None
    request = opts.PKG
    t = get_epoch_time_from_str(opts.time) if opts.time else None

    if opts.paths is None:
        pkg_paths = (config.nonlocal_packages_path if opts.no_local else None)
    else:
        pkg_paths = opts.paths.split(os.pathsep)
        pkg_paths = [os.path.expanduser(x) for x in pkg_paths if x]

    if opts.input:
        if opts.PKG:
            parser.error(
                "Cannot use --input and provide PKG(s) at the same time")
        context = ResolvedContext.load(opts.input)
        if context.status != ResolverStatus.solved:
            print >> sys.stderr, "cannot rez-env into a failed context"
            sys.exit(1)

    if opts.patch:
        # TODO: patching is lagging behind in options, and needs to be updated
        # anyway.
        if context is None:
            from rez.status import status
            context = status.context
            if context is None:
                print >> sys.stderr, "cannot patch: not in a context"
                sys.exit(1)

        request = context.get_patched_request(request,
                                              strict=opts.strict,
                                              rank=opts.patch_rank)
        context = None

    if context is None:
        # create package filters
        if opts.no_filters:
            package_filter = PackageFilterList()
        else:
            package_filter = PackageFilterList.singleton.copy()

        for rule_str in (opts.exclude or []):
            rule = Rule.parse_rule(rule_str)
            package_filter.add_exclusion(rule)

        for rule_str in (opts.include or []):
            rule = Rule.parse_rule(rule_str)
            package_filter.add_inclusion(rule)

        # perform the resolve
        context = ResolvedContext(package_requests=request,
                                  timestamp=t,
                                  package_paths=pkg_paths,
                                  building=opts.build,
                                  package_filter=package_filter,
                                  add_implicit_packages=(not opts.no_implicit),
                                  verbosity=opts.verbose,
                                  max_fails=opts.max_fails,
                                  time_limit=opts.time_limit,
                                  caching=(not opts.no_cache))

    success = (context.status == ResolverStatus.solved)
    if not success:
        context.print_info(buf=sys.stderr)

    if opts.output:
        if opts.output == '-':  # print to stdout
            context.write_to_buffer(sys.stdout)
        else:
            context.save(opts.output)
        sys.exit(0 if success else 1)

    if not success:
        sys.exit(1)

    # generally shells will behave as though the '-s' flag was not present when
    # no stdin is available. So here we replicate this behaviour.
    if opts.stdin and not select.select([sys.stdin], [], [], 0.0)[0]:
        opts.stdin = False

    quiet = opts.quiet or bool(command)
    returncode, _, _ = context.execute_shell(
        shell=opts.shell,
        rcfile=opts.rcfile,
        norc=opts.norc,
        command=command,
        stdin=opts.stdin,
        quiet=quiet,
        start_new_session=opts.new_session,
        detached=opts.detached,
        pre_command=opts.pre_command,
        block=True)

    sys.exit(returncode)
Example #31
0
def command(opts, parser, extra_arg_groups=None):
    from rez.suite import Suite
    from rez.status import status
    from rez.exceptions import SuiteError
    from rez.resolved_context import ResolvedContext
    import sys

    context_needed = set(("add", "prefix", "suffix", "hide", "unhide", "alias",
                          "unalias", "interactive"))
    save_needed = set(("add", "remove", "bump", "prefix", "suffix", "hide",
                       "unhide", "alias", "unalias"))

    def _pr(s):
        if opts.verbose:
            print s

    def _option(name):
        value = getattr(opts, name)
        if value and name in context_needed and not opts.context:
            parser.error("--context must be supplied when using --%s"
                         % name.replace('_', '-'))
        return value

    if opts.list:
        suites = status.suites
        if suites:
            for suite in suites:
                print suite.load_path
        else:
            print "No visible suites."
        sys.exit(0)

    if not opts.DIR:
        parser.error("DIR required.")

    if opts.create:
        suite = Suite()
        _pr("create empty suite at %r..." % opts.DIR)
        suite.save(opts.DIR)  # raises if dir already exists
        sys.exit(0)

    suite = Suite.load(opts.DIR)

    if _option("interactive"):
        context = suite.context(opts.context)
        retcode, _, _ = context.execute_shell(block=True)
        sys.exit(retcode)
    elif _option("validate"):
        try:
            suite.validate()
        except SuiteError as e:
            print >> sys.stderr, "The suite is invalid:\n%s" % str(e)
            sys.exit(1)
        print "The suite is valid."
    elif _option("find_request") or _option("find_resolve"):
        context_names = suite.find_contexts(in_request=opts.find_request,
                                            in_resolve=opts.find_resolve)
        if context_names:
            print '\n'.join(context_names)
    elif _option("print_tools"):
        suite.print_tools(verbose=opts.verbose, context_name=opts.context)
    elif _option("add"):
        _pr("loading context at %r..." % opts.add)
        context = ResolvedContext.load(opts.add)
        _pr("adding context %r..." % opts.context)
        suite.add_context(name=opts.context, context=context,
                          prefix_char=opts.prefix_char)
    elif _option("remove"):
        _pr("removing context %r..." % opts.remove)
        suite.remove_context(name=opts.remove)
    elif _option("bump"):
        _pr("bumping context %r..." % opts.bump)
        suite.bump_context(name=opts.bump)
    elif _option("prefix"):
        _pr("prefixing context %r..." % opts.context)
        suite.set_context_prefix(name=opts.context, prefix=opts.prefix)
    elif _option("suffix"):
        _pr("suffixing context %r..." % opts.context)
        suite.set_context_suffix(name=opts.context, suffix=opts.suffix)
    elif _option("hide"):
        _pr("hiding tool %r in context %r..." % (opts.hide, opts.context))
        suite.hide_tool(context_name=opts.context, tool_name=opts.hide)
    elif _option("unhide"):
        _pr("unhiding tool %r in context %r..." % (opts.unhide, opts.context))
        suite.unhide_tool(context_name=opts.context, tool_name=opts.unhide)
    elif _option("alias"):
        _pr("aliasing tool %r as %r in context %r..."
            % (opts.alias[0], opts.alias[1], opts.context))
        suite.alias_tool(context_name=opts.context,
                         tool_name=opts.alias[0],
                         tool_alias=opts.alias[1])
    elif _option("unalias"):
        _pr("unaliasing tool %r in context %r..." % (opts.unalias, opts.context))
        suite.unalias_tool(context_name=opts.context, tool_name=opts.unalias)
    elif _option("which"):
        filepath = suite.get_tool_filepath(opts.which)
        if filepath:
            print filepath
            sys.exit(0)
        else:
            sys.exit(1)
    elif opts.context:
        context = suite.context(opts.context)
        context.print_info(verbosity=opts.verbose)
    else:
        suite.print_info(verbose=opts.verbose)
        sys.exit(0)

    do_save = any(getattr(opts, x) for x in save_needed)
    if do_save:
        _pr("saving suite to %r..." % opts.DIR)
        suite.save(opts.DIR)