Merge pull request #1099 from sirosen/type-datetime
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Rebase of #423 to add docs, hopefully ready for merge
authored by David Lord · committed by GitHub · parents 3e17a3d, 5fe0b7e · Browse files · 6 files·+102 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+102 added−4 removed
- tests:+39 added−1 removed
- other:+63 added−3 removed
Provenance
- Commit
2c622ee- Tree
826f5f3- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
3e17a3d- Parent 2
5fe0b7e
6 files changed+102 added−4 removed
modified:click/__init__.py+4 added-3 removed
26 unmodified lines27 password_option, version_option, help_option28 29 # Types30 from .types import ParamType, File, Path, Choice, IntRange, Tuple, \31- STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange31+ DateTime, STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange32 33 # Utilities34 from .utils import echo, get_binary_stream, get_text_stream, open_file, \35 format_filename, get_app_dir, get_os_args28 unmodified lines64 'argument', 'option', 'confirmation_option', 'password_option',65 'version_option', 'help_option',66 67 # Types68- 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',69- 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange',68+ 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple',69+ 'DateTime', 'STRING', 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',70+ 'FloatRange',71 72 # Utilities73 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',74 'format_filename', 'get_app_dir', 'get_os_args',25 unmodified linesmodified:click/types.py+54 added
1 import os2 import stat3+from datetime import datetime4 5 from ._compat import open_stream, text_type, filename_to_ui, \6 get_filesystem_encoding, get_streerror, _get_argv_encoding, PY27 from .exceptions import BadParameter174 unmodified lines182 def __repr__(self):183 return 'Choice(%r)' % list(self.choices)184 185 186+class DateTime(ParamType):187+ """The DateTime type converts date strings into `datetime` objects.188+189+ The format strings which are checked are configurable, but default to some190+ common (non-timezone aware) ISO 8601 formats.191+192+ When specifying *DateTime* formats, you should only pass a list or a tuple.193+ Other iterables, like generators, may lead to surprising results.194+195+ The format strings are processed using ``datetime.strptime``, and this196+ consequently defines the format strings which are allowed.197+198+ Parsing is tried using each format, in order, and the first format which199+ parses successfully is used.200+201+ :param formats: A list or tuple of date format strings, in the order in202+ which they should be tried. Defaults to203+ ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,204+ ``'%Y-%m-%d %H:%M:%S'``.205+ """206+ name = 'datetime'207+208+ def __init__(self, formats=None):209+ self.formats = formats or [210+ '%Y-%m-%d',211+ '%Y-%m-%dT%H:%M:%S',212+ '%Y-%m-%d %H:%M:%S'213+ ]214+215+ def get_metavar(self, param):216+ return '[{}]'.format('|'.join(self.formats))217+218+ def _try_to_convert_date(self, value, format):219+ try:220+ return datetime.strptime(value, format)221+ except ValueError:222+ return None223+224+ def convert(self, value, param, ctx):225+ # Exact match226+ for format in self.formats:227+ dtime = self._try_to_convert_date(value, format)228+ if dtime:229+ return dtime230+231+ self.fail(232+ 'invalid datetime format: {}. (choose from {})'.format(233+ value, ', '.join(self.formats)))234+235+ def __repr__(self):236+ return 'DateTime'237+238+239 class IntParamType(ParamType):240 name = 'integer'241 242 def convert(self, value, param, ctx):426 unmodified linesmodified:docs/parameters.rst+3 added
68 unmodified lines69 70 .. autoclass:: FloatRange71 :noindex:72 73+.. autoclass:: DateTime74+ :noindex:75+76 Custom parameter types can be implemented by subclassing77 :class:`click.ParamType`. For simple cases, passing a Python function that78 fails with a `ValueError` is also supported, though discouraged.79 60 unmodified linesmodified:tests/test_basic.py+38 added
330 unmodified lines331 result = runner.invoke(cli, ['--help'])332 assert '--method [foo|bar|baz]' in result.output333 334 335+def test_datetime_option_default(runner):336+337+ @click.command()338+ @click.option('--start_date', type=click.DateTime())339+ def cli(start_date):340+ click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))341+342+ result = runner.invoke(cli, ['--start_date=2015-09-29'])343+ assert not result.exception344+ assert result.output == '2015-09-29T00:00:00\n'345+346+ result = runner.invoke(cli, ['--start_date=2015-09-29T09:11:22'])347+ assert not result.exception348+ assert result.output == '2015-09-29T09:11:22\n'349+350+ result = runner.invoke(cli, ['--start_date=2015-09'])351+ assert result.exit_code == 2352+ assert ('Invalid value for "--start_date": '353+ 'invalid datetime format: 2015-09. '354+ '(choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)'355+ ) in result.output356+357+ result = runner.invoke(cli, ['--help'])358+ assert '--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]' in result.output359+360+361+def test_datetime_option_custom(runner):362+ @click.command()363+ @click.option('--start_date',364+ type=click.DateTime(formats=['%A %B %d, %Y']))365+ def cli(start_date):366+ click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))367+368+ result = runner.invoke(cli, ['--start_date=Wednesday June 05, 2010'])369+ assert not result.exception370+ assert result.output == '2010-06-05T00:00:00\n'371+372+373 def test_int_range_option(runner):374 @click.command()375 @click.option('--x', type=click.IntRange(0, 5))376 def cli(x):160 unmodified linesmodified:tests/test_imports.py+1 added-1 removed
30 unmodified lines31 32 ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35- 'threading', 'colorama', 'errno', 'fcntl'35+ 'threading', 'colorama', 'errno', 'fcntl', 'datetime'36 ])37 38 if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',16 unmodified linesmodified:CHANGES.rst+2 added
13 unmodified lines14 - Document byte-stripping behavior of ``CliRunner``. (`#334`_, `#1010`_)15 - Usage errors now hint at the ``--help`` option. (`#393`_, `#557`_)16 - Implement streaming pager. (`#409`_, `#889`_)17 - Extract bar formatting to its own method. (`#414`_)18+- Add ``DateTime`` type for converting input in given date time formats. (`#423`_)19 - ``secho``'s first argument can now be ``None``, like in ``echo``. (`#424`_)20 - Fixes a ``ZeroDivisionError`` in ``ProgressBar.make_step``, when the arg passed to the first call of ``ProgressBar.update`` is 0. (`#447`_, `#1012`_)21 - Show progressbar only if total execution time is visible. (`#487`_)22 - Added the ability to hide commands and options from help. (`#500`_)70 unmodified lines93 .. _#334: https://github.com/pallets/click/issues/33494 .. _#393: https://github.com/pallets/click/issues/39395 .. _#409: https://github.com/pallets/click/issues/40996 .. _#414: https://github.com/pallets/click/pull/41497+.. _#423: https://github.com/pallets/click/pull/42398 .. _#424: https://github.com/pallets/click/pull/42499 .. _#447: https://github.com/pallets/click/issues/447100 .. _#487: https://github.com/pallets/click/pull/487101 .. _#500: https://github.com/pallets/click/pull/500449 unmodified lines