Skip to content

Commit

Permalink
modest refactor of attr validator code
Browse files Browse the repository at this point in the history
  • Loading branch information
kouk committed Oct 27, 2016
1 parent afe1aaa commit 63b0ae6
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
4 changes: 2 additions & 2 deletions mgship/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from mgship import mgship
from mgship.destination import csv, json
from mgship.cliparam import DateTime, Loglevel
from mgship.util import utctimestamp, validate_past
from mgship.util import utctimestamp, is_past
from mgship.log import logger


Expand All @@ -26,7 +26,7 @@ def to_timestamp(ctx, param, value):
try:
value = utctimestamp(value)
if ctx.info_name == 'archive':
validate_past(value)
is_past(value)
return value
except (TypeError, ValueError) as e:
logger.debug("bad timestamp parameter", exc_info=True)
Expand Down
21 changes: 17 additions & 4 deletions mgship/mgship.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,32 @@
from __future__ import absolute_import
import attr

from functools import wraps

from mgship.api import Client
from mgship.events import mg_past_events
from mgship.util import validate_past
from mgship.util import is_past
from mgship.log import logger


def mg_field_validator(wrapped):
"""Convert a simple validator method to a attr.ib validator.
Given a method which accepts a value and possibly raises ValueError
create a attr compatible validator that accepts empty values.
"""
@attr.validators.optional
@wraps(wrapped)
def wrapper(*args, **kwargs):
return wrapped(*args[2:], **kwargs)
return wrapper


@attr.s
class Archive(object):
"""Ship all existing events."""
dest = attr.ib()
begin = attr.ib(default=None,
validator=attr.validators.optional(
lambda i, a, v: validate_past(v)))
begin = attr.ib(default=None, validator=mg_field_validator(is_past))
_client = attr.ib(default=attr.Factory(Client), repr=False)
_filtered_params = ['dest', '_client']

Expand Down
4 changes: 2 additions & 2 deletions mgship/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from datetime import datetime, timedelta

__all__ = ['utctimestamp', 'timenow', 'timeago', 'fromtimestamp',
'validate_past']
'is_past']


def utctimestamp(now=None):
Expand All @@ -28,7 +28,7 @@ def timeago(**kwargs):
return timenow() - timedelta(**kwargs)


def validate_past(value):
def is_past(value):
"""Validator for timestamps in the past.
Raises ValueError if value is not a timestamp that represents
Expand Down

0 comments on commit 63b0ae6

Please sign in to comment.