bchao1 / bullet

🚅 Interactive prompts made simple. Build a prompt like stacking blocks.
https://pypi.org/project/bullet/
MIT License
3.55k stars 113 forks source link

Add Date prompt #74

Open a-luna opened 3 years ago

a-luna commented 3 years ago

First, I have to say thank you for creating Bullet. I am using it to create a menu-driven UI in one of my projects, and it has been wonderful to use.

While using Bullet, I have created several custom prompts and I would love to contribute them back to the project. However, I notice that Bullet currently does not include any external dependencies and implementing my additions would require this to change.

In this PR, I have created a Date prompt that extends Input. It can parse a date from many different string formats thanks to the parser module in the python-dateutil package. Please note that this is an extremely mature package, as it was first released in 2003 and is currently managed by the PSF.

I also included a wrap_text function that makes printing any arbitrarily long string to the console much better. Using the max_len argument, it returns a new string that is wrapped and does not break in the middle of words. It is used when the value entered by the user failed to parse, since the error message that is displayed is somewhat verbose.

If no external dependencies is a hard-requirement, please feel free to close this PR. If it is not, I will submit additional PRs with other prompts I have created. Thank you again for creating this awesome utility!

Basic Usage

from bullet import Date

d = Date("Enter birthdate:")
birthdate = d.launch()
print(repr(birthdate))

Output

Enter birthdate:1/15/1984
datetime.date(1984, 1, 15)

Error Handling, Default Value

from datetime import date
from bullet import Date

d = Date("Enter birthdate:", default=date(1980, 1, 1))
birthdate = d.launch()
print(repr(birthdate))

Output

Enter birthdate:[01/01/1980]test
Error! 'test' could not be parsed as a valid date.

You can use any format recognized by dateutil.parser. For example, all 
of the strings below are valid ways to represent the same date:

"2018-5-13" -or- "05/13/2018" -or- "May 13 2018"

Enter birthdate:[01/01/1980]Jan 15 1984
datetime.date(1984, 1, 15)

Customize Default Value Format

from datetime import date
from bullet import Date

d = Date(
    "Enter start date:",
    default=date(2020 10, 20),
    format_str="%b %d %Y",
)

started = d.launch()
print(repr(started))

Output

Enter start date:[Oct 20 2020]
# user accepts default value
datetime.date(2020, 10, 20)
a-luna commented 3 years ago

Updated DOCUMENTATION.md to include Date prompt