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 39positional arguments: 40 source_dir application source directory 41 cmake_opt extra options to pass to cmake; implies -c 42 (these must come after "--" as shown above) 43''' 44 45 46class Completion(WestCommand): 47 48 def __init__(self): 49 super().__init__( 50 'completion', 51 # Keep this in sync with the string in west-commands.yml. 52 'output shell completion scripts', 53 COMP_DESCRIPTION, 54 accepts_unknown_args=False) 55 56 def do_add_parser(self, parser_adder): 57 parser = parser_adder.add_parser( 58 self.name, 59 help=self.help, 60 formatter_class=argparse.RawDescriptionHelpFormatter, 61 description=self.description) 62 63 # Remember to update west-completion.bash if you add or remove 64 # flags 65 parser.add_argument('shell', nargs=1, choices=['bash', 'zsh', 'fish'], 66 help='''Shell that which the completion 67 script is intended for.''') 68 return parser 69 70 def do_run(self, args, unknown_args): 71 cf = os.path.join(os.path.dirname(os.path.realpath(__file__)), 72 *COMPLETION_REL_PATH.split('/')) 73 74 cf += '.' + args.shell[0] 75 76 try: 77 with open(cf, 'r') as f: 78 print(f.read()) 79 except FileNotFoundError as e: 80 self.die('Unable to find completion file: {}'.format(e)) 81