Skip to content

Commit

Permalink
converters/file: can now be used without being called
Browse files Browse the repository at this point in the history
  • Loading branch information
epsy committed Apr 7, 2017
1 parent c06c5c0 commit 10c5a72
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
12 changes: 10 additions & 2 deletions clize/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import os
from functools import partial

from clize import parser, errors
from sigtools.modifiers import autokwoargs

from clize import parser, errors, util


@parser.value_converter(name='TIME')
Expand Down Expand Up @@ -71,7 +73,10 @@ def _none_guard(cls, maybe_none, *args, **kwargs):
else:
return cls(maybe_none, *args, **kwargs)

def file(stdio='-', keep_stdio_open=False, **kwargs):

@parser.value_converter(name='FILE', convert_default=True)
@autokwoargs(exceptions=['arg'])
def file(arg=util.UNSET, stdio='-', keep_stdio_open=False, **kwargs):
"""Takes a file argument and provides a Python object that opens a file
::
Expand Down Expand Up @@ -101,11 +106,14 @@ def main(inf: file()='-'):
"""
if arg is not util.UNSET:
return _none_guard(_FileOpener, arg, kwargs, stdio, keep_stdio_open)
return parser.value_converter(
partial(_none_guard, _FileOpener, kwargs=kwargs,
stdio=stdio, keep_stdio_open=keep_stdio_open),
name='FILE', convert_default=True)


def _convert_ioerror(arg, exc):
nexc = errors.ArgumentError('{0.strerror}: {1!r}'.format(exc, arg))
nexc.__cause__ = exc
Expand Down
15 changes: 15 additions & 0 deletions clize/tests/test_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,21 @@ def func(afile):
self.assertFalse(e.getvalue())
self.assertTrue(self.completed)

def test_not_called(self):
path = os.path.join(self.temp, 'afile')
open(path, 'w').close()
@modifiers.annotate(afile=converters.file)
def func(afile):
with afile as f:
self.assertEqual(f.name, path)
self.assertEqual(f.mode, 'r')
self.assertTrue(f.closed)
self.completed = True
o, e = self.crun(func, ['test', path])
self.assertFalse(o.getvalue())
self.assertFalse(e.getvalue())
self.assertTrue(self.completed)

def test_file_write(self):
path = os.path.join(self.temp, 'afile')
@modifiers.annotate(afile=converters.file(mode='w'))
Expand Down

0 comments on commit 10c5a72

Please sign in to comment.