1# Copyright (c) 2019 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import argparse
6import os
7
8from west import log
9from west.commands import WestCommand
10
11# Relative to the folder where this script lives
12COMPLETION_REL_PATH = 'completion/west-completion'
13
14class Completion(WestCommand):
15
16    def __init__(self):
17        super().__init__(
18            'completion',
19            # Keep this in sync with the string in west-commands.yml.
20            'display shell completion scripts',
21            'Display shell completion scripts.',
22            accepts_unknown_args=False)
23
24    def do_add_parser(self, parser_adder):
25        parser = parser_adder.add_parser(
26            self.name,
27            help=self.help,
28            formatter_class=argparse.RawDescriptionHelpFormatter,
29            description=self.description)
30
31        # Remember to update west-completion.bash if you add or remove
32        # flags
33        parser.add_argument('shell', nargs=1, choices=['bash'],
34                            help='''Select the shell that which the completion
35                            script is intended for.
36                            Currently only bash is supported.''')
37        return parser
38
39    def do_run(self, args, unknown_args):
40        cf = os.path.join(os.path.dirname(os.path.realpath(__file__)),
41                          *COMPLETION_REL_PATH.split('/'))
42
43        cf += '.' + args.shell[0]
44
45        try:
46            with open(cf, 'r') as f:
47                print(f.read())
48        except FileNotFoundError as e:
49            log.die('Unable to find completion file: {}'.format(e))
50