/usr/share/pyshared/checkbox_cli/cli_interface.py is in checkbox-cli 0.13.7.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | #
# This file is part of Checkbox.
#
# Copyright 2008 Canonical Ltd.
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox. If not, see <http://www.gnu.org/licenses/>.
#
import re
import sys
import string
import termios
from gettext import gettext as _
from checkbox.user_interface import (UserInterface, ANSWER_TO_STATUS,
ALL_ANSWERS, YES_ANSWER, NO_ANSWER, SKIP_ANSWER)
ANSWER_TO_OPTION = {
YES_ANSWER: _("yes"),
NO_ANSWER: _("no"),
SKIP_ANSWER: _("skip")}
OPTION_TO_ANSWER = dict((o, a) for a, o in ANSWER_TO_OPTION.items())
class CLIDialog(object):
"""Command line dialog wrapper."""
def __init__(self, text):
self.text = text
self.visible = False
def put(self, text):
sys.stdout.write(text)
def put_line(self, line):
self.put("%s\n" % line)
def put_newline(self):
self.put("\n")
def get(self, label=None, limit=1, separator=termios.CEOT):
if label is not None:
self.put_newline()
self.put(label)
fileno = sys.stdin.fileno()
saved_attributes = termios.tcgetattr(fileno)
attributes = termios.tcgetattr(fileno)
attributes[3] = attributes[3] & ~(termios.ICANON | termios.ECHO)
attributes[6][termios.VMIN] = 1
attributes[6][termios.VTIME] = 0
termios.tcsetattr(fileno, termios.TCSANOW, attributes)
input = []
escape = 0
try:
while len(input) < limit:
ch = str(sys.stdin.read(1))
if ord(ch) == separator:
break
elif ord(ch) == 033: # ESC
escape = 1
elif ord(ch) == termios.CERASE or ord(ch) == 010:
if len(input):
self.put("\010 \010")
del input[-1]
elif ord(ch) == termios.CKILL:
self.put("\010 \010" * len(input))
input = []
else:
if not escape:
input.append(ch)
self.put(ch)
elif escape == 1:
if ch == "[":
escape = 2
else:
escape = 0
elif escape == 2:
escape = 0
finally:
termios.tcsetattr(fileno, termios.TCSANOW, saved_attributes)
return "".join(input)
def show(self):
self.visible = True
self.put_newline()
self.put_line(self.text)
class CLIChoiceDialog(CLIDialog):
def __init__(self, text):
super(CLIChoiceDialog, self).__init__(text)
self.keys = []
self.options = []
def get(self, *args, **kwargs):
response = super(CLIChoiceDialog, self).get(*args, **kwargs)
try:
return self.keys.index(response[0])
except ValueError:
return -1
def run(self, label=None, defaults=[]):
if not self.visible:
self.show()
try:
# Only one option
if len(self.keys) <= 1:
self.get(_("Press any key to continue..."))
return 0
# Multiple choices
while True:
self.put_newline()
for key, option in zip(self.keys, self.options):
default = "*" if option in defaults else " "
self.put_line("%s %s: %s" % (default, key, option))
response = self.get(_("Please choose (%s): ") % ("/".join(self.keys)))
if response >= 0:
return response
if label is not None:
self.put_line(label)
except KeyboardInterrupt:
self.put_newline()
raise
def add_option(self, option, key=None):
if key is None:
keys = option.lower() + \
string.ascii_letters + \
string.digits + \
string.punctuation
keys = keys.replace(' ','')
keys = keys.replace('+', '')
for key in keys:
if key not in self.keys:
break
self.keys.append(key)
self.options.append(option)
class CLIReportDialog(CLIDialog):
"""
Display test results
"""
STATUS = {'pass': '[0;32m{0}[0m',
'fail': '[0;31m{0}[0m'}
def __init__(self, text, results):
super(CLIReportDialog, self).__init__(text)
self.results = results
def run(self):
"""
Show root of the tree
and provide the ability to further display subtress
"""
root = self.results
title = self.text
self._display(title, root)
def _is_suite(self, root):
"""
Return True if root contains a suite
that is, a job containing other jobs
"""
return all(issubclass(type(value), dict)
for value in root.itervalues())
def _display(self, title, root):
"""
Display dialog until user decides to exit
(recursively for subtrees)
"""
while True:
self.put_newline()
self.put_newline()
self.put_line(title)
self.put_newline()
keys = []
options = []
def add_option(option, key=None):
"""
Add option to list
and generate automatic key value
if not provided
"""
if key is None:
key = string.lowercase[len(keys)]
keys.append(key)
options.append(option)
for job_name, job_data in sorted(root.iteritems()):
if self._is_suite(job_data):
add_option(job_name)
self.put_line('{key}: {option}'
.format(key=keys[-1],
option=options[-1]))
else:
job_status = job_data.get('status')
status_string = (self.STATUS.get(job_status, '{0}')
.format(job_status))
self.put_line(' {name} [{status}]'
.format(name=job_name,
status=status_string))
add_option(_("Space when finished"), " ")
self.put_line('{key}: {option}'
.format(key=keys[-1],
option=options[-1]))
response = self.get(_("Please choose (%s): ") % ("/".join(keys)))
if response != ' ':
try:
selected_option = options[keys.index(response)]
except ValueError:
# Display again menu
continue
# Display new menu with the contents of the selected option
self._display(selected_option, root[selected_option])
else:
# Exit from this menu display
# (display again parent menu or exit)
break
class CLITextDialog(CLIDialog):
limit = 255
separator = termios.CEOT
def run(self, label=None):
if not self.visible:
self.show()
self.put_newline()
try:
return self.get(label, self.limit, self.separator)
except KeyboardInterrupt:
self.put_newline()
raise
class CLILineDialog(CLITextDialog):
limit = 80
separator = ord("\n")
class CLIProgressDialog(CLIDialog):
"""Command line progress dialog wrapper."""
def __init__(self, text):
super(CLIProgressDialog, self).__init__(text)
self.progress_count = 0
def set(self, progress=None):
self.progress_count = (self.progress_count + 1) % 5
if self.progress_count:
return
if progress != None:
self.put("\r%u%%" % (progress * 100))
else:
self.put(".")
sys.stdout.flush()
class CLIInterface(UserInterface):
def _toggle_results(self, key, options, results):
if isinstance(results, dict):
if key in results:
del results[key]
elif key in options:
if isinstance(options[key], dict):
results[key] = {}
elif isinstance(options[key], (list, tuple,)):
results[key] = []
else:
results[key] = None
for k in options[key]:
self._toggle_results(k, options[key], results[key])
elif isinstance(results, (list, tuple,)):
if key in results:
results.remove(key)
elif key in options:
results.append(key)
def show_progress_start(self, text):
self.progress = CLIProgressDialog(text)
self.progress.show()
def show_progress_pulse(self):
self.progress.set()
def show_text(self, text, previous=None, next=None):
dialog = CLIChoiceDialog(text)
dialog.run()
def show_entry(self, text, value, previous=None, next=None):
dialog = CLILineDialog(text)
return dialog.run()
def show_check(self, text, options=[], default=[]):
dialog = CLIChoiceDialog(text)
for option in options:
dialog.add_option(option)
dialog.add_option(_("Space when finished"), " ")
results = default
while True:
response = dialog.run(defaults=results)
if response >= len(options):
break
result = options[response]
self._toggle_results(result, options, results)
return results
def show_radio(self, text, options=[], default=None):
dialog = CLIChoiceDialog(text)
for option in options:
dialog.add_option(option)
# Show options dialog
response = dialog.run()
return options[response]
def show_tree(self, text, options={}, default={}):
keys = sorted(options.keys())
dialog = CLIChoiceDialog(text)
for option in keys:
dialog.add_option(option)
dialog.add_option(_("Combine with character above to expand node"), "+")
dialog.add_option(_("Space when finished"), " ")
do_expand = False
results = default
while True:
response = dialog.run(defaults=results)
if response > len(options):
break
elif response == len(options):
response = dialog.get()
do_expand = True
else:
do_expand = False
# Invalid response
if response < 0:
continue
# Toggle results
result = keys[response]
if not do_expand:
self._toggle_results(result, options, results)
continue
# Expand tree
dialog.visible = False
if options[result]:
branch_results = results.get(result, {})
self.show_tree(result, options[result], branch_results)
if branch_results and result not in results:
results[result] = branch_results
return results
def show_report(self, text, results):
"""
Show test case results in a tree hierarchy
"""
dialog = CLIReportDialog(text, results)
dialog.run()
def show_test(self, test, runner):
options = list([ANSWER_TO_OPTION[a] for a in ALL_ANSWERS])
if "command" in test:
options.append(_("test"))
if re.search(r"\$output", test["description"]):
output = runner(test)[1]
else:
output = ""
while True:
# Show option dialog
description = string.Template(test["description"]).substitute({
"output": output.strip()})
dialog = CLIChoiceDialog(description)
for option in options:
dialog.add_option(option, option[0])
# Get option from dialog
response = dialog.run()
option = options[response]
if response < len(ALL_ANSWERS):
break
output = runner(test)[1]
options[-1] = _("test again")
answer = OPTION_TO_ANSWER[option]
if answer == NO_ANSWER:
text = _("Further information:")
dialog = CLITextDialog(text)
test["data"] = dialog.run(_("Please type here and press"
" Ctrl-D when finished:\n"))
else:
test["data"] = ""
test["status"] = ANSWER_TO_STATUS[answer]
def show_info(self, text, options=[], default=None):
return self.show_radio(text, options, default)
def show_error(self, text):
dialog = CLIChoiceDialog("Error: %s" % text)
dialog.run()
|