1# Copyright (c) 2019 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import argparse
6import os
7
8from west.commands import WestCommand
9
10# Relative to the folder where this script lives
11COMPLETION_REL_PATH = 'completion/west-completion'
12
13COMP_DESCRIPTION = '''\
14Output shell completion scripts for west.
15
16This command outputs completion scripts for different shells by printing them
17to stdout. Using the completion scripts:
18
19  bash:
20    # one-time
21    source <(west completion bash)
22    # permanent
23    west completion bash > ~/west-completion.bash
24    # edit your .bashrc or .bash_profile and add:
25    source $HOME/west-completion.bash
26
27  zsh:
28    # one-time
29    source <(west completion zsh)
30    # permanent (might require sudo)
31    west completion zsh > "${fpath[1]}/_west"
32
33  fish:
34    # one-time
35    west completion fish | source
36    # permanent
37    west completion fish > $HOME/.config/fish/completions/west.fish
38
39  powershell:
40    # one-time
41    west completion powershell | Out-String | Invoke-Expression
42    # permanent
43    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
44    New-item -type file -force $PROFILE
45    (Add-Content -Path $PROFILE -Value ". '{$HOME/west-completion.ps1}'")
46
47positional arguments:
48  source_dir            application source directory
49  cmake_opt             extra options to pass to cmake; implies -c
50                        (these must come after "--" as shown above)
51'''
52
53
54class Completion(WestCommand):
55    _EXT_MAPPING = {
56        "bash": "bash",
57        "fish": "fish",
58        "powershell": "ps1",
59        "zsh": "zsh",
60    }
61
62    def __init__(self):
63        super().__init__(
64            'completion',
65            # Keep this in sync with the string in west-commands.yml.
66            'output shell completion scripts',
67            COMP_DESCRIPTION,
68            accepts_unknown_args=False)
69
70    def do_add_parser(self, parser_adder):
71        parser = parser_adder.add_parser(
72            self.name,
73            help=self.help,
74            formatter_class=argparse.RawDescriptionHelpFormatter,
75            description=self.description)
76
77        # Remember to update west-completion.bash if you add or remove
78        # flags
79        parser.add_argument('shell', nargs=1, choices=self._EXT_MAPPING.keys(),
80                            help='''Shell that which the completion
81                            script is intended for.''')
82        return parser
83
84    def do_run(self, args, unknown_args):
85        cf = os.path.join(os.path.dirname(os.path.realpath(__file__)),
86                          *COMPLETION_REL_PATH.split('/'))
87
88        cf += '.' + self._EXT_MAPPING[args.shell[0]]
89
90        try:
91            with open(cf) as f:
92                print(f.read())
93        except FileNotFoundError as e:
94            self.die(f'Unable to find completion file: {e}')
95