1# Copyright (c) 2023 Google
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import argparse
6import os
7import sys
8
9from west import log
10from west.commands import WestCommand
11
12from zephyr_ext_common import ZEPHYR_SCRIPTS
13
14# Resolve path to twister libs and add imports
15twister_path = ZEPHYR_SCRIPTS
16os.environ["ZEPHYR_BASE"] = str(twister_path.parent)
17
18sys.path.insert(0, str(twister_path))
19sys.path.insert(0, str(twister_path / "pylib" / "twister"))
20
21from twisterlib.environment import add_parse_arguments, parse_arguments
22from twisterlib.twister_main import main
23
24TWISTER_DESCRIPTION = """\
25Convenience wrapper for twister. The below options are shared with the twister
26script and have the same effects as if you ran twister directly. Refer to the
27twister documentation for more information.
28"""
29
30
31class Twister(WestCommand):
32    def __init__(self):
33        super(Twister, self).__init__(
34            "twister",
35            # Keep this in sync with the string in west-commands.yml.
36            "west twister wrapper",
37            TWISTER_DESCRIPTION,
38            accepts_unknown_args=True,
39        )
40
41    def do_add_parser(self, parser_adder):
42        parser = parser_adder.add_parser(
43            self.name,
44            help=self.help,
45            formatter_class=argparse.RawDescriptionHelpFormatter,
46            description=self.description,
47            allow_abbrev=False
48        )
49
50        parser = add_parse_arguments(parser)
51
52        return parser
53
54    def do_run(self, args, remainder):
55        log.dbg(
56            "args: {} remainder: {}".format(args, remainder), level=log.VERBOSE_EXTREME
57        )
58
59        options = self._parse_arguments(args=remainder, options=args)
60        ret = main(options)
61        sys.exit(ret)
62
63    def _parse_arguments(self, args, options):
64        """Helper function for testing purposes"""
65        return parse_arguments(self.parser, args, options)
66