Debian Codegraph @

examples/hooks.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A sample application for cmd2 demonstrating how to use hooks.
3
4 This application shows how to use postparsing hooks to allow case insensitive
5 command names, abbreviated commands, as well as allowing numeric arguments to
6 follow a command without any intervening whitespace.
7
8 """
9
10 import re
11
12 import cmd2
13
14
15 class CmdLineApp(cmd2.Cmd):
16 """Example cmd2 application demonstrating the use of hooks.
17
18 This simple application has one command, `list` which generates a list
19 of 10 numbers. This command takes one optional argument, which is the
20 number to start on.
21
22 We have three postparsing hooks, which allow the user to enter:
23
24 (Cmd) list 5
25 (Cmd) L 5
26 (Cmd) l 5
27 (Cmd) L5
28 (Cmd) LI5
29
30 and have them all treated as valid input which prints a list of 10 numbers
31 starting with the number 5.
32
33 We also add a postcommand hook, which updates the shell prompt to show the
34 raw contents of the Statement after the postparsing hooks are finished. To
35 use this hook, run `(Cmd) set debug True`. All of the above variations of
36 the list command should produce the same raw content.
37
38 """
39
40 def __init__(self, *args, **kwargs) -> None:
41 super().__init__(*args, **kwargs)
42
43 # register four hooks
44 self.register_postparsing_hook(self.add_whitespace_hook)
45 self.register_postparsing_hook(self.downcase_hook)
46 self.register_postparsing_hook(self.abbrev_hook)
47 self.register_postcmd_hook(self.proof_hook)
48
49 def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
50 """A hook to split alphabetic command names immediately followed by a number.
51
52 l24 -> l 24
53 list24 -> list 24
54 list 24 -> list 24
55
56 """
57 command = data.statement.command
58 # regular expression with looks for:
59 # ^ - the beginning of the string
60 # ([^\s\d]+) - one or more non-whitespace non-digit characters, set as capture group 1
61 # (\d+) - one or more digit characters, set as capture group 2
62 command_pattern = re.compile(r"^([^\s\d]+)(\d+)")
63 match = command_pattern.search(command)
64 if match:
65 command = match.group(1)
66 first_arg = match.group(2)
67 rest_args = data.statement.args
68 post_command = data.statement.post_command
69 data.statement = self.statement_parser.parse(f"{command} {first_arg} {rest_args} {post_command}")
70 return data
71
72 def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
73 """A hook to make uppercase commands lowercase."""
74 command = data.statement.command.lower()
75 args = data.statement.args
76 post_command = data.statement.post_command
77 data.statement = self.statement_parser.parse(f"{command} {args} {post_command}")
78 return data
79
80 def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
81 """Accept unique abbreviated commands."""
82 func = self.get_command_func(data.statement.command)
83 if func is None:
84 # check if the entered command might be an abbreviation
85 possible_cmds = [cmd for cmd in self.get_all_commands() if cmd.startswith(data.statement.command)]
86 if len(possible_cmds) == 1:
87 raw = data.statement.raw.replace(data.statement.command, possible_cmds[0], 1)
88 data.statement = self.statement_parser.parse(raw)
89 return data
90
91 def proof_hook(self, data: cmd2.plugin.PostcommandData) -> cmd2.plugin.PostcommandData:
92 """Update the shell prompt with the new raw statement after postparsing hooks are finished."""
93 if self.debug:
94 self.prompt = f"({data.statement.raw})"
95 return data
96
97 @cmd2.with_argument_list
98 def do_list(self, arglist: list[str]) -> None:
99 """Generate a list of 10 numbers."""
100 if arglist:
101 first = arglist[0]
102 try:
103 first = int(first)
104 except ValueError:
105 first = 1
106 else:
107 first = 1
108 last = first + 10
109
110 for x in range(first, last):
111 self.poutput(str(x))
112
113
114 if __name__ == "__main__":
115 import sys
116
117 c = CmdLineApp()
118 sys.exit(c.cmdloop())