1# Copyright (c) 2018 Foundries.io
2#
3# SPDX-License-Identifier: Apache-2.0
4
5'''Helpers shared by multiple west extension command modules.
6
7Note that common helpers used by the flash and debug extension
8commands are in run_common -- that's for common code used by
9commands which specifically execute runners.'''
10
11import os
12import shlex
13from pathlib import Path
14
15from west.commands import WestCommand
16
17# This relies on this file being zephyr/scripts/foo/bar.py.
18# If you move this file, you'll break it, so be careful.
19THIS_ZEPHYR = Path(__file__).parent.parent.parent
20ZEPHYR_BASE = Path(os.environ.get('ZEPHYR_BASE', THIS_ZEPHYR))
21
22# FIXME we need a nicer way to handle imports from scripts and cmake than this.
23ZEPHYR_SCRIPTS = ZEPHYR_BASE / 'scripts'
24ZEPHYR_CMAKE = ZEPHYR_BASE / 'cmake'
25
26class Forceable(WestCommand):
27    '''WestCommand subclass for commands with a --force option.'''
28
29    @staticmethod
30    def add_force_arg(parser):
31        '''Add a -f / --force option to the parser.'''
32        parser.add_argument('-f', '--force', action='store_true',
33                            help='ignore any errors and try to proceed')
34
35    def check_force(self, cond, msg):
36        '''Abort if the command needs to be forced and hasn't been.
37
38        The "forced" predicate must be in self.args.forced.
39
40        If cond and self.args.force are both False, scream and die
41        with message msg. Otherwise, return. That is, "cond" is a
42        condition which means everything is OK; if it's False, only
43        self.args.force being True can allow execution to proceed.
44        '''
45        if not (cond or self.args.force):
46            self.err(msg)
47            self.die('refusing to proceed without --force due to above error')
48
49    def config_get_words(self, section_key, fallback=None):
50        unparsed = self.config.get(section_key)
51        self.dbg(f'west config {section_key}={unparsed}')
52        return fallback if unparsed is None else shlex.split(unparsed)
53
54    def config_get(self, section_key, fallback=None):
55        words = self.config_get_words(section_key)
56        if words is None:
57            return fallback
58        if len(words) != 1:
59            self.die(f'Single word expected for: {section_key}={words}. Use quotes?')
60        return words[0]
61