Skip to content

Commit 7facfb5

Browse files
committed
Add arrow-key menus for experiment and input choices
1 parent cb968bd commit 7facfb5

7 files changed

Lines changed: 187 additions & 41 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ abench /path/to/model
4949

5050
Abench looks for `.yaml` and `.yml` files directly inside `/path/to/model/.abench/`
5151
(no recursive search). In a terminal it lists them alphabetically and asks which
52-
experiment to run, then prompts for that experiment's inputs. Enter chooses the
53-
first file; a single file still gets a selection prompt. Only the selected file
52+
experiment to run, then prompts for that experiment's inputs. Use ↑/↓ to move the highlighted selection and Enter to confirm. The first file
53+
is initially selected; a single file still gets a selection prompt. Only the selected file
5454
is loaded. `run`, `validate`, and `prepare` all support directory selection.
5555

5656
`abench /path/to/model --help` lists available files without prompting or running
@@ -196,7 +196,10 @@ vars:
196196
```
197197

198198
In a terminal, run, validate, and prepare prompt for each input in YAML order.
199-
Press Enter to accept a displayed default. Required inputs have no default and
199+
Inputs with `choices` use the same arrow-key menu, with the declared default
200+
initially highlighted (or the first option if required). Enter confirms the
201+
selection and preserves its declared type. Other inputs use text prompts.
202+
Press Enter to accept a displayed default. Required text inputs have no default and
200203
must be entered; empty or invalid answers prompt again with an explanation.
201204
Ctrl-C cancels before source resolution or downloads. Selected values are printed
202205
and saved in `suite.json` as `input_values`.

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ readme = "README.md"
1010
requires-python = ">=3.10"
1111
license = "BSD-3-Clause"
1212
license-files = ["LICENSE"]
13-
dependencies = ["PyYAML>=6", "platformdirs>=3", "zstandard>=0.21"]
13+
dependencies = ["PyYAML>=6", "platformdirs>=3", "zstandard>=0.21", "prompt_toolkit>=3.0.36,<4"]
1414
keywords = ["activitysim", "benchmark", "transportation", "memory", "sharrow"]
1515
classifiers = [
1616
"Development Status :: 3 - Alpha",

‎src/abench/discovery.py‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Discover and choose experiment instructions stored inside a model directory."""
22

3+
from .menus import choose
4+
35

46
def instruction_files(directory):
57
"""List immediate YAML files deterministically without loading any suite."""
@@ -46,20 +48,7 @@ def select_experiment(path, interactive):
4648
+ ", ".join(p.name for p in files)
4749
+ ". Run in a terminal to choose, or pass the experiment YAML path directly."
4850
)
49-
print(f"Experiments in {path / '.abench'}:", flush=True)
50-
for number, file in enumerate(files, 1):
51-
print(f" {number}. {file.name}", flush=True)
52-
while True:
53-
try:
54-
answer = input(f"Choose experiment [1] (1–{len(files)}): ").strip()
55-
except EOFError as error:
56-
raise ValueError(
57-
"Input ended while choosing an experiment; nothing started"
58-
) from error
59-
if not answer:
60-
answer = "1"
61-
if answer.isascii() and answer.isdigit() and 1 <= int(answer) <= len(files):
62-
chosen = files[int(answer) - 1]
63-
print(f"Selected experiment: {chosen.name}", flush=True)
64-
return chosen
65-
print(f"Enter a number from 1 to {len(files)}.", flush=True)
51+
selected = choose(
52+
f"Experiment in {path / '.abench'}", [file.name for file in files]
53+
)
54+
return files[selected]

‎src/abench/inputs.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import math
44
import re
55

6+
from .menus import choose
7+
68
TYPES = {
79
"string": (str,),
810
"integer": (int,),
@@ -169,6 +171,11 @@ def prompt_value(name, spec):
169171
"""Keep asking until the user supplies a valid value or accepts a default."""
170172
if spec.get("description"):
171173
print(f"{name}: {spec['description']}", flush=True)
174+
if "choices" in spec:
175+
options = spec["choices"]
176+
default_index = options.index(spec["default"]) if "default" in spec else 0
177+
selected = choose(name, [str(value) for value in options], default_index)
178+
return check_value(name, spec, options[selected])
172179
constraints = ", ".join(
173180
f"{key}: {spec[key]}"
174181
for key in ("choices", "minimum", "maximum")

‎src/abench/menus.py‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
"""Keyboard-driven choices shared by experiment discovery and typed inputs."""
2+
3+
from prompt_toolkit.application import Application
4+
from prompt_toolkit.data_structures import Point
5+
from prompt_toolkit.key_binding import KeyBindings
6+
from prompt_toolkit.layout import HSplit, Layout, Window
7+
from prompt_toolkit.layout.controls import FormattedTextControl
8+
from prompt_toolkit.layout.dimension import Dimension
9+
10+
11+
def choose(title, labels, default_index=0):
12+
"""Return an index on Enter; preserve defaults and restore the terminal on exit."""
13+
if not labels or not 0 <= default_index < len(labels):
14+
raise ValueError("choice menu requires options and a valid initial selection")
15+
selected = default_index
16+
bindings = KeyBindings()
17+
18+
@bindings.add("up")
19+
def up(event):
20+
nonlocal selected
21+
selected = (selected - 1) % len(labels)
22+
23+
@bindings.add("down")
24+
def down(event):
25+
nonlocal selected
26+
selected = (selected + 1) % len(labels)
27+
28+
@bindings.add("enter")
29+
def accept(event):
30+
event.app.exit(result=selected)
31+
32+
@bindings.add("c-c")
33+
def cancel(event):
34+
event.app.exit(exception=KeyboardInterrupt())
35+
36+
@bindings.add("c-d")
37+
def eof(event):
38+
event.app.exit(exception=EOFError())
39+
40+
def render():
41+
# Plain formatted-text fragments avoid interpreting labels as markup.
42+
# Reverse video + a marker remain visible without color support.
43+
fragments = []
44+
for index, label in enumerate(labels):
45+
label = " ".join(str(label).splitlines())
46+
fragments.append(
47+
(
48+
"bold reverse" if index == selected else "",
49+
f"{'>' if index == selected else ' '} {label}",
50+
)
51+
)
52+
if index < len(labels) - 1:
53+
fragments.append(("", "\n"))
54+
return fragments
55+
56+
control = FormattedTextControl(
57+
render,
58+
focusable=True,
59+
show_cursor=False,
60+
get_cursor_position=lambda: Point(x=0, y=selected),
61+
)
62+
app = Application(
63+
layout=Layout(
64+
HSplit(
65+
[
66+
Window(
67+
FormattedTextControl(title + " (↑/↓ to move, Enter to choose)"),
68+
height=1,
69+
),
70+
# A bounded viewport scrolls to the selection for long lists.
71+
Window(control, height=Dimension(max=10), wrap_lines=False),
72+
]
73+
),
74+
focused_element=control,
75+
),
76+
key_bindings=bindings,
77+
full_screen=False,
78+
erase_when_done=True,
79+
)
80+
try:
81+
result = app.run()
82+
except EOFError as error:
83+
raise ValueError(
84+
"Input ended while choosing; experiment not started"
85+
) from error
86+
print(f"{title}: {labels[result]}", flush=True)
87+
return result

‎tests/test_discovery.py‎

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,22 +15,26 @@ def instructions(tmp_path):
1515
return folder
1616

1717

18-
def test_selection_order_and_invalid_answers(tmp_path, monkeypatch, capsys):
18+
def test_selection_order(tmp_path, monkeypatch):
1919
folder = instructions(tmp_path)
20-
assert [p.name for p in instruction_files(tmp_path)] == ["a.yaml", "b.yml"]
21-
answers = iter(["bad", "0", "3", "2"])
22-
monkeypatch.setattr("builtins.input", lambda prompt: next(answers))
20+
21+
def choose(title, labels):
22+
assert labels == ["a.yaml", "b.yml"]
23+
return 1
24+
25+
monkeypatch.setattr("abench.discovery.choose", choose)
2326
assert select_experiment(tmp_path, True) == folder / "b.yml"
24-
assert "Enter a number" in capsys.readouterr().out
2527

2628

27-
def test_single_file_still_prompts_and_accepts_enter(tmp_path, monkeypatch):
29+
def test_single_file_still_prompts(tmp_path, monkeypatch):
2830
folder = instructions(tmp_path)
2931
(folder / "b.yml").unlink()
3032
prompts = []
31-
monkeypatch.setattr("builtins.input", lambda prompt: prompts.append(prompt) or "")
33+
monkeypatch.setattr(
34+
"abench.discovery.choose", lambda title, labels: prompts.append(labels) or 0
35+
)
3236
assert select_experiment(tmp_path, True) == folder / "a.yaml"
33-
assert len(prompts) == 1
37+
assert prompts == [["a.yaml"]]
3438
assert select_experiment(tmp_path, False) == folder / "a.yaml"
3539

3640

@@ -46,17 +50,6 @@ def test_noninteractive_multiple_and_missing(tmp_path):
4650
instruction_files(tmp_path)
4751

4852

49-
def test_selection_eof(tmp_path, monkeypatch):
50-
instructions(tmp_path)
51-
52-
def ended(prompt):
53-
raise EOFError()
54-
55-
monkeypatch.setattr("builtins.input", ended)
56-
with pytest.raises(ValueError, match="nothing started"):
57-
select_experiment(tmp_path, True)
58-
59-
6053
def test_directory_help_does_not_prompt_or_parse_suites(tmp_path, monkeypatch, capsys):
6154
instructions(tmp_path)
6255

@@ -85,7 +78,11 @@ def test_choice_then_inputs_and_file_relative_paths(tmp_path, monkeypatch):
8578
households: ${households}
8679
""")
8780
prompts = []
88-
answers = iter(["2", "42"])
81+
answers = iter(["42"])
82+
monkeypatch.setattr(
83+
"abench.discovery.choose",
84+
lambda title, labels: prompts.append("Choose experiment") or 1,
85+
)
8986

9087
def respond(prompt):
9188
prompts.append(prompt)

‎tests/test_menus.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""Exercise real arrow-key bindings without needing a physical terminal."""
2+
3+
import pytest
4+
from prompt_toolkit.application import create_app_session
5+
from prompt_toolkit.input import create_pipe_input
6+
from prompt_toolkit.output import DummyOutput
7+
8+
from abench.inputs import resolve_inputs
9+
from abench.menus import choose
10+
11+
12+
@pytest.mark.parametrize(
13+
"keys,initial,expected",
14+
[
15+
("\r", 1, 1),
16+
("\x1b[B\r", 0, 1),
17+
("\x1b[A\r", 1, 0),
18+
("\x1b[A\r", 0, 2),
19+
("\x1b[B\r", 2, 0),
20+
],
21+
)
22+
def test_navigation(keys, initial, expected):
23+
with (
24+
create_pipe_input() as pipe,
25+
create_app_session(input=pipe, output=DummyOutput()),
26+
):
27+
pipe.send_text(keys)
28+
assert choose("Mode", ["First", "Second", "Third"], initial) == expected
29+
30+
31+
@pytest.mark.parametrize(
32+
"key,error", [("\x03", KeyboardInterrupt), ("\x04", ValueError)]
33+
)
34+
def test_cancellation(key, error):
35+
with (
36+
create_pipe_input() as pipe,
37+
create_app_session(input=pipe, output=DummyOutput()),
38+
):
39+
pipe.send_text(key)
40+
with pytest.raises(error):
41+
choose("Mode", ["First"])
42+
43+
44+
def test_typed_choice_defaults_and_required(monkeypatch):
45+
calls = []
46+
47+
def pick(title, labels, initial):
48+
calls.append((labels, initial))
49+
return initial
50+
51+
monkeypatch.setattr("abench.inputs.choose", pick)
52+
values, _ = resolve_inputs(
53+
{
54+
"inputs": {
55+
"count": {"type": "integer", "choices": [2, 4, 8], "default": 4},
56+
"mode": {"type": "string", "choices": ["a", "b"], "required": True},
57+
}
58+
},
59+
[],
60+
interactive=True,
61+
)
62+
assert calls == [(["2", "4", "8"], 1), (["a", "b"], 0)]
63+
assert values == {"count": 4, "mode": "a"}

0 commit comments

Comments
 (0)