Skip to content

Update cmd2.Cmd.select to use prompt-toolkit choice#1600

Open
tleonhardt wants to merge 5 commits intomainfrom
pt-choice
Open

Update cmd2.Cmd.select to use prompt-toolkit choice#1600
tleonhardt wants to merge 5 commits intomainfrom
pt-choice

Conversation

@tleonhardt
Copy link
Member

The choice function from prompt-toolkit is now used for cmd2.Cmd.select method when both stdin and stdout are TTYs.

Key Changes:

  • prompt_toolkit.shortcuts.choice integration: The select method now utilizes the modern, interactive choice shortcut when both stdin and stdout are TTYs. This provides a more user-friendly selection menu (usually supports arrow keys and searching).
  • Backward Compatibility: Maintained the original numbered-list implementation as a fallback for non-TTY environments. This ensures that existing scripts, pipes, and tests (which mock read_input) continue to function correctly.
  • Robust Argument Handling: Standardized the conversion of various input formats (strings, lists of strings, lists of tuples) to the (value, label) format required by choice.
  • Error Handling: Wrapped the choice call in a loop and a try-except block to correctly handle KeyboardInterrupt (Ctrl-C) by printing ^C and re-raising, and to handle cancellations by reprompting, maintaining consistency with original select behavior.

Key Changes:
   - prompt_toolkit.shortcuts.choice integration: The select method now utilizes the modern, interactive choice shortcut when both stdin and stdout are TTYs. This
     provides a more user-friendly selection menu (usually supports arrow keys and searching).
   - Backward Compatibility: Maintained the original numbered-list implementation as a fallback for non-TTY environments. This ensures that existing scripts,
     pipes, and tests (which mock read_input) continue to function correctly.
   - Robust Argument Handling: Standardized the conversion of various input formats (strings, lists of strings, lists of tuples) to the (value, label) format
     required by choice.
   - Error Handling: Wrapped the choice call in a loop and a try-except block to correctly handle KeyboardInterrupt (Ctrl-C) by printing ^C and re-raising, and to
     handle cancellations by reprompting, maintaining consistency with original select behavior.
@tleonhardt tleonhardt requested a review from kmvanbrunt as a code owner March 7, 2026 02:44
@github-actions
Copy link
Contributor

github-actions bot commented Mar 7, 2026

🤖 Hi @tleonhardt, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@tleonhardt tleonhardt self-assigned this Mar 7, 2026
@tleonhardt tleonhardt added this to the 4.0.0 milestone Mar 7, 2026
@codecov
Copy link

codecov bot commented Mar 7, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.51%. Comparing base (e5d2de7) to head (9c50259).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1600   +/-   ##
=======================================
  Coverage   99.51%   99.51%           
=======================================
  Files          21       21           
  Lines        4714     4725   +11     
=======================================
+ Hits         4691     4702   +11     
  Misses         23       23           
Flag Coverage Δ
unittests 99.51% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 7, 2026

🤖 I'm sorry @tleonhardt, but I was unable to process your request. Please see the logs for more details.

@tleonhardt tleonhardt mentioned this pull request Mar 7, 2026
20 tasks
super().__init__()
self.remove_settable('debug')

def do_eat(self, arg):
Copy link
Member

@kmvanbrunt kmvanbrunt Mar 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why put an example for select() in the example about removing Settables?

except (IndexError, TypeError):
fulloptions.append((opt[0], str(opt[0])))

if self.stdin.isatty() and self.stdout.isatty():
Copy link
Member

@kmvanbrunt kmvanbrunt Mar 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest changing this to if self._is_tty_session(self.main_session):

Otherwise the choice function won't run when in a pyscript or when redirecting the output of a command.

monkeypatch.setattr("cmd2.cmd2.choice", choice_mock)

# Mock isatty to be True for both stdin and stdout
monkeypatch.setattr(outsim_app.stdin, "isatty", lambda: True)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you make the logic change I suggested in select(), replace these isatty monkeypatches with something like this:

with create_pipe_input() as pipe_input:
        base_app.main_session = PromptSession(
            input=pipe_input,
            output=DummyOutput(),
    )

    prompt = 'Sauce? '
    options = ['sweet', 'salty']
    ...

Do the same for the next test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants