Skip to content
Myr

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

6 files+102 added−4 removed

modified:click/__init__.py+4 added-3 removed
26 unmodified lines
27 password_option, version_option, help_option2829# Types30from .types import ParamType, File, Path, Choice, IntRange, Tuple, \31 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange31 DateTime, STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange3233# Utilities34from .utils import echo, get_binary_stream, get_text_stream, open_file, \35 format_filename, get_app_dir, get_os_args
28 unmodified lines
64 'argument', 'option', 'confirmation_option', 'password_option',65 'version_option', 'help_option',6667 # 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',7172 # Utilities73 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',74 'format_filename', 'get_app_dir', 'get_os_args',
25 unmodified lines
modified:click/types.py+54 added
1import os2import stat3from datetime import datetime45from ._compat import open_stream, text_type, filename_to_ui, \6 get_filesystem_encoding, get_streerror, _get_argv_encoding, PY27from .exceptions import BadParameter
174 unmodified lines
182 def __repr__(self):183 return 'Choice(%r)' % list(self.choices)184185186class DateTime(ParamType):187 """The DateTime type converts date strings into `datetime` objects.188189 The format strings which are checked are configurable, but default to some190 common (non-timezone aware) ISO 8601 formats.191192 When specifying *DateTime* formats, you should only pass a list or a tuple.193 Other iterables, like generators, may lead to surprising results.194195 The format strings are processed using ``datetime.strptime``, and this196 consequently defines the format strings which are allowed.197198 Parsing is tried using each format, in order, and the first format which199 parses successfully is used.200201 :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'207208 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 ]214215 def get_metavar(self, param):216 return '[{}]'.format('|'.join(self.formats))217218 def _try_to_convert_date(self, value, format):219 try:220 return datetime.strptime(value, format)221 except ValueError:222 return None223224 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 dtime230231 self.fail(232 'invalid datetime format: {}. (choose from {})'.format(233 value, ', '.join(self.formats)))234235 def __repr__(self):236 return 'DateTime'237238239class IntParamType(ParamType):240 name = 'integer'241242 def convert(self, value, param, ctx):
426 unmodified lines
modified:docs/parameters.rst+3 added
68 unmodified lines
6970.. autoclass:: FloatRange71 :noindex:7273.. autoclass:: DateTime74 :noindex:7576Custom parameter types can be implemented by subclassing77:class:`click.ParamType`. For simple cases, passing a Python function that78fails with a `ValueError` is also supported, though discouraged.79
60 unmodified lines
modified:tests/test_basic.py+38 added
330 unmodified lines
331 result = runner.invoke(cli, ['--help'])332 assert '--method [foo|bar|baz]' in result.output333334335def test_datetime_option_default(runner):336337 @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'))341342 result = runner.invoke(cli, ['--start_date=2015-09-29'])343 assert not result.exception344 assert result.output == '2015-09-29T00:00:00\n'345346 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'349350 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.output356357 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.output359360361def 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'))367368 result = runner.invoke(cli, ['--start_date=Wednesday June 05, 2010'])369 assert not result.exception370 assert result.output == '2010-06-05T00:00:00\n'371372373def test_int_range_option(runner):374 @click.command()375 @click.option('--x', type=click.IntRange(0, 5))376 def cli(x):
160 unmodified lines
modified:tests/test_imports.py+1 added-1 removed
30 unmodified lines
3132ALLOWED_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])3738if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',
16 unmodified lines
modified:CHANGES.rst+2 added
13 unmodified lines
14- 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 lines
93.. _#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/500
449 unmodified lines