laravel / prompts

Beautiful and user-friendly forms for your command-line PHP applications.
https://laravel.com/docs/prompts
MIT License
533 stars 94 forks source link

Allow customizing the cancel behaviour #100

Closed weitzman closed 10 months ago

weitzman commented 11 months ago

I'm coming from the Drush project, the CLI for Drupal. We are switching our prompts to use this package.

One minor gotcha is calling exit() when a user cancels a prompt. Prompts renders a nice Cancelled message and then calls exit(1) which triggers PHP shutdown handling. It would be more convenient if an Exception is thrown here, so implementing projects can react appropriately. A shutdown handler is too restricted in what it can do.

This PR is just a start so I can get feedback on the idea. Maybe we make the this behavior configurable?

Thanks for releasing Prompts as an independant package!

taylorotwell commented 11 months ago

Will let @jessarcher take a look. 👍

jessarcher commented 10 months ago

Hey @weitzman, thanks for the PR! Very cool that you're adding Prompts to Drush!

This PR is just a start so I can get feedback on the idea. Maybe we make the this behavior configurable?

I think making it configurable might be the go, otherwise, all existing projects using Prompts won't exit cleanly on Ctrl+c until they add a handler:

image

We could add a handler in laravel/framework that will cover most projects, but there are others (such as laravel/installer and various third-party non-Laravel projects) that would also be impacted.

I'm thinking a static method on the Prompt class that accepts a callback. E.g:

Prompt::cancelUsing(fn () => throw new Exception);

If no callback has been registered, the default exit(1) behaviour can be retained.

What do you think?

weitzman commented 10 months ago

Sounds good to me. See latest push. I've confirmed this is working with the Drush PR. I looked at the tests and don't see a way to test this. I'm happy to add a test if anyone can think of one.

taylorotwell commented 10 months ago

Drafting until @jessarcher takes a look again.

jessarcher commented 10 months ago

Thanks @weitzman! I've added a quick test.