Skip to content

Commit

Permalink
introduce interactive select for menus
Browse files Browse the repository at this point in the history
  • Loading branch information
bradjc committed Aug 31, 2022
1 parent e873c16 commit 315f2f4
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,6 @@
"pyserial >= 3.0.1",
"toml >= 0.10.2",
"tqdm >= 4.45.0 ",
"questionary >= 1.10.0",
],
)
39 changes: 38 additions & 1 deletion tockloader/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import sys

import colorama
import questionary


def set_terminal_title(title):
Expand All @@ -27,7 +28,7 @@ def set_terminal_title_from_port_info(info):
if info.description and info.description != "n/a":
extras.append(info.description)
# if info.hwid and info.hwid != 'n/a':
# extras.append(info.hwid)
# extras.append(info.hwid)
if info.product and info.product != "n/a":
if info.product != info.description:
extras.append(info.product)
Expand All @@ -43,6 +44,42 @@ def set_terminal_title_from_port(port):
set_terminal_title("Tockloader : {}".format(port))


def menu_new(options, *, return_type, default_index=None, prompt="", title=""):
"""
Present an interactive menu of choices to a user.
`options` should be a like-list object whose iterated objects can be coerced
into strings.
`return_type` must be set to one of:
- "index" - for the index into the options array
- "value" - for the option value chosen
`default_index` is the index to present as the default value (what happens
if the user simply presses enter). Passing `None` disables default
selection.
"""

prompt_to_show = prompt
if len(title) > len(prompt_to_show):
prompt_to_show = title

default = None
if default_index:
default = options[default_index]

response = questionary.select(
prompt_to_show, choices=options, default=default, qmark=""
).ask()

if return_type == "index":
return options.index(response)
elif return_type == "value":
return response
else:
raise NotImplementedError("Menu caller asked for bad return_type")


def menu(options, *, return_type, default_index=0, prompt="Which option? ", title=""):
"""
Present a menu of choices to a user
Expand Down
2 changes: 1 addition & 1 deletion tockloader/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ def command_inspect_tab(args):

# Ask the user if they want to see more detail about a certain TBF.
tbf_names = tab.get_tbf_names()
index = helpers.menu(
index = helpers.menu_new(
tbf_names + ["None"],
return_type="index",
title="Which TBF to inspect further?",
Expand Down

0 comments on commit 315f2f4

Please sign in to comment.