1# Copyright (c) 2023 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4from __future__ import annotations
5
6import logging
7import shlex
8
9from subprocess import check_output
10from pathlib import Path
11
12
13logger = logging.getLogger(__name__)
14
15
16def west_sign_with_imgtool(
17        build_dir: Path,
18        output_bin: Path | None = None,
19        key_file: Path | None = None,
20        version: str | None = None,
21        timeout: int = 10
22):
23    """Wrapper method for `west sign -t imgtool` comamnd"""
24    command = [
25        'west', 'sign',
26        '-t', 'imgtool',
27        '--no-hex',
28        '--build-dir', str(build_dir)
29    ]
30    if output_bin:
31        command.extend(['--sbin', str(output_bin)])
32
33    command_extra_args = []
34    if key_file:
35        command_extra_args.extend(['--key', str(key_file)])
36    if version:
37        command_extra_args.extend(['--version', version])
38
39    if command_extra_args:
40        command.append('--')
41        command.extend(command_extra_args)
42
43    logger.info(f"CMD: {shlex.join(command)}")
44    output = check_output(command, text=True, timeout=timeout)
45    logger.debug('OUT: %s' % output)
46