1# Copyright (c) 2020 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import argparse
6from pathlib import Path
7from shutil import rmtree
8
9from west.commands import WestCommand
10from west import log
11
12from zcmake import run_cmake
13
14EXPORT_DESCRIPTION = '''\
15This command registers the current Zephyr installation as a CMake
16config package in the CMake user package registry.
17
18In Windows, the CMake user package registry is found in:
19HKEY_CURRENT_USER\\Software\\Kitware\\CMake\\Packages\\
20
21In Linux and MacOS, the CMake user package registry is found in:
22~/.cmake/packages/'''
23
24
25class ZephyrExport(WestCommand):
26
27    def __init__(self):
28        super().__init__(
29            'zephyr-export',
30            # Keep this in sync with the string in west-commands.yml.
31            'export Zephyr installation as a CMake config package',
32            EXPORT_DESCRIPTION,
33            accepts_unknown_args=False)
34
35    def do_add_parser(self, parser_adder):
36        parser = parser_adder.add_parser(
37            self.name,
38            help=self.help,
39            formatter_class=argparse.RawDescriptionHelpFormatter,
40            description=self.description)
41        return parser
42
43    def do_run(self, args, unknown_args):
44        # The 'share' subdirectory of the top level zephyr repository.
45        share = Path(__file__).parents[2] / 'share'
46
47        run_cmake_export(share / 'zephyr-package' / 'cmake')
48        run_cmake_export(share / 'zephyrunittest-package' / 'cmake')
49
50def run_cmake_export(path):
51    # Run a package installation script.
52    #
53    # Filtering out lines that start with -- ignores the normal
54    # CMake status messages and instead only prints the important
55    # information.
56
57    lines = run_cmake(['-P', str(path / 'zephyr_export.cmake')],
58                      capture_output=True)
59    msg = [line for line in lines if not line.startswith('-- ')]
60    log.inf('\n'.join(msg))
61
62def remove_if_exists(pathobj):
63    if pathobj.is_file():
64        log.inf(f'- removing: {pathobj}')
65        pathobj.unlink()
66    elif pathobj.is_dir():
67        log.inf(f'- removing: {pathobj}')
68        rmtree(pathobj)
69