1# Copyright (c) 2024 Vestas Wind Systems A/S
2# Copyright (c) 2019 Nordic Semiconductor ASA
3#
4# SPDX-License-Identifier: Apache-2.0
5
6import argparse
7import os
8import re
9import sys
10import textwrap
11from pathlib import Path
12
13from west.commands import WestCommand
14from zephyr_ext_common import ZEPHYR_BASE
15
16sys.path.append(os.fspath(Path(__file__).parent.parent))
17import list_shields
18import zephyr_module
19
20
21class Shields(WestCommand):
22
23    def __init__(self):
24        super().__init__(
25            'shields',
26            # Keep this in sync with the string in west-commands.yml.
27            'display list of supported shield',
28            'Display supported shields',
29            accepts_unknown_args=False)
30
31    def do_add_parser(self, parser_adder):
32        default_fmt = '{name}'
33        parser = parser_adder.add_parser(
34            self.name,
35            help=self.help,
36            formatter_class=argparse.RawDescriptionHelpFormatter,
37            description=self.description,
38            epilog=textwrap.dedent(f'''\
39            FORMAT STRINGS
40            --------------
41
42            Shields are listed using a Python 3 format string. Arguments
43            to the format string are accessed by name.
44
45            The default format string is:
46
47            "{default_fmt}"
48
49            The following arguments are available:
50
51            - name: shield name
52            - dir: directory that contains the shield definition
53            '''))
54
55        # Remember to update west-completion.bash if you add or remove
56        # flags
57        parser.add_argument('-f', '--format', default=default_fmt,
58                            help='''Format string to use to list each shield;
59                                    see FORMAT STRINGS below.''')
60        parser.add_argument('-n', '--name', dest='name_re',
61                            help='''a regular expression; only shields whose
62                            names match NAME_RE will be listed''')
63        list_shields.add_args(parser)
64
65        return parser
66
67    def do_run(self, args, _):
68        if args.name_re is not None:
69            name_re = re.compile(args.name_re)
70        else:
71            name_re = None
72
73        modules_board_roots = [ZEPHYR_BASE]
74
75        for module in zephyr_module.parse_modules(ZEPHYR_BASE, self.manifest):
76            board_root = module.meta.get('build', {}).get('settings', {}).get('board_root')
77            if board_root is not None:
78                modules_board_roots.append(Path(module.project) / board_root)
79
80        args.board_roots += modules_board_roots
81
82        for shield in list_shields.find_shields(args):
83            if name_re is not None and not name_re.search(shield.name):
84                continue
85            self.inf(args.format.format(name=shield.name, dir=shield.dir))
86