使用west工具的幫助命令,west -h,不僅可以列出west工具的內置命令,也可以列舉當前工程中實現的擴展命令,如build,flash等。
本文將介紹如何添加擴展命令。
west擴展命令的位置通過以下方式查找:
1. 首先找到工程中.west目錄的config文件,打開config,查看以下兩個值:
????????1)path參數的值,默認為zephyr。
????????2)file參數的值,默認為west.yml。
[manifest]
path = zephyr
file = west.yml[zephyr]
base = zephyr
2)根據path參數和file參數的值,找到對應的文件,默認為zephyr/west.yml。
在west.yml文件中,可以看到以下配置,即west擴展命令在scripts/west-commands.yml文件中定義。
self:path: zephyrwest-commands: scripts/west-commands.ymlimport: submanifests
3)如下代碼所示,west-commands.yml文件中列舉了當前工程支持的擴展命令,以及每個擴展命令的名稱和對應的python文件。
# Keep the help strings in sync with the values in the .py files!
west-commands:- file: scripts/west_commands/completion.pycommands:- name: completionclass: Completionhelp: output shell completion scripts- file: scripts/west_commands/boards.pycommands:- name: boardsclass: Boardshelp: display information about supported boards- file: scripts/west_commands/build.pycommands:- name: buildclass: Buildhelp: compile a Zephyr application
接下來,可以按照以下步驟添加一個新的擴展命令。
1)在west-commands.yml文件中添加一個新的命令。命名為new_cmd,對應的python文件為new_cmd_file.py。
注:file,name,class,help可以根據需要添加任意名稱和字符串。
# Keep the help strings in sync with the values in the .py files!
west-commands:- file: scripts/west_commands/new_cmd_file.pycommands:- name: new_cmdclass: new_cmd_classhelp: this is a new command- file: scripts/west_commands/completion.pycommands:- name: completionclass: Completionhelp: output shell completion scripts- file: scripts/west_commands/boards.pycommands:- name: boardsclass: Boardshelp: display information about supported boards
2)在west_commands目錄中添加west-commands.yml文件中定義的文件new_cmd_file.py。
其中,class應該與west-commands.yml文件中定義的class一致。此外,需要實現do_add_parser和do_run函數,這兩個函數將在執行west擴展命令時自動被調用。
import argparse
from zephyr_ext_common import ForceableUSAGE = '''\
This is new command USAGE.
'''DESCRIPTION = f'''\
This is new command DESCRIPTION.
'''class new_cmd_class(Forceable):def __init__(self):super(new_cmd_class, self).__init__('new_cmd',# Keep this in sync with the string in west-commands.yml.'this is a new command',DESCRIPTION,accepts_unknown_args=True)print("__init__ function of new command!")def do_add_parser(self, parser_adder):parser = parser_adder.add_parser(self.name,help=self.help,formatter_class=argparse.RawDescriptionHelpFormatter,description=self.description,usage=USAGE)print("do_add_parser function of new command!")return parserdef do_run(self, args, remainder):print("do_run function of new command!")
通過west -h幫助命令查看以上擴展命令是否成功添加。可以看出,擴展命令中已經包含new_cmd命令。
執行擴展命令,west new_cmd,如下log所示,__init__函數,do_add_parser函數和do_run函數依次被調用。
通過以上步驟,新的擴展命令已經添加完成,接下來可以根據需求進一步開發,完善擴展命令。