/
command.py
377 lines (293 loc) · 9.51 KB
/
command.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
from __future__ import annotations
import inspect
import re
from typing import TYPE_CHECKING
from typing import Any
from cleo.commands.base_command import BaseCommand
from cleo.formatters.style import Style
from cleo.io.inputs.string_input import StringInput
from cleo.io.null_io import NullIO
from cleo.io.outputs.output import Verbosity
from cleo.parser import Parser
from cleo.ui.table_separator import TableSeparator
if TYPE_CHECKING:
from cleo.io.io import IO
from cleo.ui.progress_bar import ProgressBar
from cleo.ui.progress_indicator import ProgressIndicator
from cleo.ui.question import Question
class Command(BaseCommand):
arguments = []
options = []
aliases = []
usages = []
commands = []
def __init__(self) -> None:
self._io: IO | None = None
super().__init__()
@property
def io(self) -> IO:
return self._io
def configure(self) -> None:
if not self.name:
doc = self.__doc__
if not doc:
for base in inspect.getmro(self.__class__):
if base.__doc__ is not None:
doc = base.__doc__
break
if doc:
self._parse_doc(doc)
for argument in self.arguments:
self._definition.add_argument(argument)
for option in self.options:
self._definition.add_option(option)
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self.description = doc[0].strip()
signature = re.sub(r"\s{2,}", " ", doc[1].strip())
definition = Parser.parse(signature)
self.name = definition["name"]
for argument in definition["arguments"]:
self._definition.add_argument(argument)
for option in definition["options"]:
self._definition.add_option(option)
else:
self.description = doc[0].strip()
def execute(self, io: IO) -> int:
self._io = io
try:
return self.handle()
except KeyboardInterrupt:
return 1
def handle(self) -> int:
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name: str, args: str | None = None) -> int:
"""
Call another command.
"""
if args is None:
args = ""
input = StringInput(args)
command = self.application.get(name)
return self.application._run_command(command, self._io.with_input(input))
def call_silent(self, name: str, args: str | None = None) -> int:
"""
Call another command silently.
"""
if args is None:
args = ""
args = StringInput(args)
command = self.application.get(name)
return self.application._run_command(command, NullIO(input))
def argument(self, name: str):
"""
Get the value of a command argument.
"""
return self._io.input.argument(name)
def option(self, name: str):
"""
Get the value of a command option.
"""
return self._io.input.option(name)
def confirm(
self, question: str, default: bool = False, true_answer_regex: str = "(?i)^y"
) -> bool:
"""
Confirm a question with the user.
"""
from cleo.ui.confirmation_question import ConfirmationQuestion
question = ConfirmationQuestion(
question, default=default, true_answer_regex=true_answer_regex
)
return question.ask(self._io)
def ask(self, question: str | Question, default: Any | None = None) -> Any:
"""
Prompt the user for input.
"""
from cleo.ui.question import Question
if not isinstance(question, Question):
question = Question(question, default=default)
return question.ask(self._io)
def secret(self, question: str | Question, default: Any | None = None) -> Any:
"""
Prompt the user for input but hide the answer from the console.
"""
from cleo.ui.question import Question
if not isinstance(question, Question):
question = Question(question)
question.hide()
return question.ask(self._io)
def choice(
self,
question: str,
choices: list[str],
default: Any | None = None,
attempts: int | None = None,
multiple: bool = False,
) -> Any:
"""
Give the user a single choice from an list of answers.
"""
from cleo.ui.choice_question import ChoiceQuestion
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return question.ask(self._io)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
from cleo.ui.choice_question import ChoiceQuestion
from cleo.ui.confirmation_question import ConfirmationQuestion
from cleo.ui.question import Question
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
from cleo.ui.table import Table
table = Table(self._io, style=style)
if header:
table.set_headers([header])
if rows:
table.set_rows(rows)
return table
def table_separator(self) -> TableSeparator:
"""
Return a TableSeparator instance.
"""
from cleo.ui.table_separator import TableSeparator
return TableSeparator()
def render_table(self, headers, rows, style=None) -> None:
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render()
def write(self, text: str, style: str | None = None) -> None:
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = f"<{style}>{text}</>"
else:
styled = text
self._io.write(styled)
def line(
self,
text: str,
style: str | None = None,
verbosity: Verbosity = Verbosity.NORMAL,
) -> None:
"""
Write a string as information output.
"""
if style:
styled = f"<{style}>{text}</>"
else:
styled = text
self._io.write_line(styled, verbosity=verbosity)
def line_error(
self,
text: str,
style: str | None = None,
verbosity: Verbosity = Verbosity.NORMAL,
) -> None:
"""
Write a string as information output to stderr.
"""
if style:
styled = f"<{style}>{text}</>"
else:
styled = text
self._io.write_error_line(styled, verbosity)
def info(self, text: str) -> None:
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text: str) -> None:
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text: str) -> None:
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max: int = 0) -> ProgressBar:
"""
Creates a new progress bar
"""
from cleo.ui.progress_bar import ProgressBar
return ProgressBar(self._io, max=max)
def progress_indicator(
self,
fmt: str | None = None,
interval: int = 100,
values: list[str] | None = None,
) -> ProgressIndicator:
"""
Creates a new progress indicator.
"""
from cleo.ui.progress_indicator import ProgressIndicator
return ProgressIndicator(self.io, fmt, interval, values)
def spin(
self,
start_message: str,
end_message: str,
fmt: str | None = None,
interval=100,
values: list[str] | None = None,
):
"""
Automatically spin a progress indicator.
"""
spinner = self.progress_indicator(fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(
self,
name: str,
fg: str | None = None,
bg: str | None = None,
options: list[str] | None = None,
) -> None:
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text: str) -> None:
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text)