Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps/subcmd.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 #
3 # This source code is licensed under the MIT license found in the
4 # LICENSE file in the root directory of this source tree.
5
6
7 class SubCmd(object):
8 NAME = None
9 HELP = None
10
11 def run(self, args) -> int:
12 """perform the command"""
13 return 0
14
15 def setup_parser(self, parser) -> None:
16 # Subclasses should override setup_parser() if they have any
17 # command line options or arguments.
18 pass
19
20
21 CmdTable = []
22
23
24 def add_subcommands(parser, common_args, cmd_table=CmdTable) -> None:
25 """Register parsers for the defined commands with the provided parser"""
26 for cls in cmd_table:
27 command = cls()
28 command_parser = parser.add_parser(
29 command.NAME, help=command.HELP, parents=[common_args]
30 )
31 command.setup_parser(command_parser)
32 command_parser.set_defaults(func=command.run)
33
34
35 def cmd(name, help=None, cmd_table=CmdTable):
36 """
37 @cmd() is a decorator that can be used to help define Subcmd instances
38
39 Example usage:
40
41 @subcmd('list', 'Show the result list')
42 class ListCmd(Subcmd):
43 def run(self, args):
44 # Perform the command actions here...
45 pass
46 """
47
48 def wrapper(cls):
49 class SubclassedCmd(cls):
50 NAME = name
51 HELP = help
52
53 cmd_table.append(SubclassedCmd)
54 return SubclassedCmd
55
56 return wrapper