Skip to content

Commit

Permalink
Reformat IOErrors in converter.file
Browse files Browse the repository at this point in the history
  • Loading branch information
epsy committed Feb 22, 2015
1 parent cc4524b commit 93bddc5
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 9 deletions.
12 changes: 8 additions & 4 deletions clize/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,21 @@ def message(self):
self.param)


class CliValueError(ValueError):
"""Specialization of `ValueError` for showing a message to the user along
with the error rather than just the incorrect value."""

class BadArgumentFormat(ArgumentError):
"""Raised when an argument cannot be converted to the correct format."""

def __init__(self, param, val):
def __init__(self, param, text):
self.param = param
self.val = val
self.text = text

@property
def message(self):
return "Bad value for {0.display_name}: {1!r}".format(
self.param, self.val)
return "Bad value for {0.display_name}: {1}".format(
self.param, self.text)


class ArgsBeforeAlternateCommand(ArgumentError):
Expand Down
12 changes: 11 additions & 1 deletion clize/extra/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,23 @@

from dateutil import parser as dparser

from clize import errors


def datetime(arg):
return dparser.parse(arg)


def file(**kwargs):
def file_(arg):
return io.open(arg, **kwargs)
try:
return io.open(arg, **kwargs)
except IOError as exc:
raise _convert_ioerror(arg, exc)

return file_

def _convert_ioerror(arg, exc):
nexc = errors.CliValueError('{0.strerror} {1!r}'.format(exc, arg))
nexc.__cause__ = exc
return nexc
13 changes: 9 additions & 4 deletions clize/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,16 +201,21 @@ def coerce_value(self, arg, ba):
"""
try:
ret = self.typ(arg)
except errors.CliValueError as e:
exc = errors.BadArgumentFormat(self, e)
exc.__cause__ = e
raise exc
except ValueError as e:
exc = errors.BadArgumentFormat(self, repr(arg))
exc.__cause__ = e
raise exc
else:
try:
type(ret).__enter__
except AttributeError:
return ret
else:
return ba.exitstack.enter_context(ret)
except ValueError as e:
exc = errors.BadArgumentFormat(self.typ, arg)
exc.__cause__ = e
raise exc

def get_value(self, ba, i):
"""Retrieves the "value" part of the argument in ``ba`` at
Expand Down
5 changes: 5 additions & 0 deletions clize/tests/extra/test_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ def test_file_write(self):
self.assertEqual(arg.mode, 'w')
self.assertTrue(arg.closed)

def test_file_missing(self):
path = os.path.join(self.temp, 'afile')
self.assertRaises(errors.BadArgumentFormat,
self.run_conv, converters.file(), path)


@util.repeated_test
class ConverterErrorTests(object):
Expand Down

0 comments on commit 93bddc5

Please sign in to comment.