|
| 1 | +from datetime import datetime |
| 2 | + |
| 3 | +GITHUB_TIMEZONE = "-0700" |
| 4 | +GITHUB_DATE_FORMAT = "%Y/%m/%d %H:%M:%S" |
| 5 | + |
| 6 | + |
| 7 | +def ghdate_to_datetime(github_date): |
| 8 | + date_without_tz = github_date.rsplit("-")[0].strip() |
| 9 | + return datetime.strptime(date_without_tz, GITHUB_DATE_FORMAT) |
| 10 | + |
| 11 | + |
| 12 | +def datetime_to_ghdate(datetime_): |
| 13 | + date_without_tz = datetime_.strftime(GITHUB_DATE_FORMAT) |
| 14 | + return " ".join([date_without_tz, GITHUB_TIMEZONE]) |
| 15 | + |
| 16 | + |
1 | 17 | class GithubCommand(object): |
2 | 18 |
|
3 | 19 | def __init__(self, request): |
@@ -36,28 +52,45 @@ def __new__(cls, name, bases, attrs): |
36 | 52 | super_new = super(BaseDataType, cls).__new__ |
37 | 53 |
|
38 | 54 | attributes = attrs.pop("attributes", tuple()) |
| 55 | + date_attributes = set(attrs.pop("date_attributes", tuple())) |
39 | 56 | attrs.update(dict([(attr_name, None) |
40 | 57 | for attr_name in attributes])) |
41 | 58 |
|
| 59 | + def _contribute_method(name, func): |
| 60 | + func.func_name = name |
| 61 | + attrs[name] = func |
| 62 | + |
42 | 63 | def constructor(self, **kwargs): |
43 | 64 | for attr_name, attr_value in kwargs.items(): |
44 | 65 | if attr_name not in attributes: |
45 | 66 | raise TypeError("%s.__init__() doesn't support the " |
46 | 67 | "%s argument." % ( cls_name, attr_name)) |
47 | 68 | setattr(self, attr_name, attr_value) |
48 | | - attrs["__init__"] = constructor |
49 | 69 |
|
50 | | - def to_dict(self): |
51 | | - dict_ = {} |
52 | | - for attr_name in self.attributes: |
53 | | - attr_value = getattr(self, attr_name, None) |
54 | | - if attr_value is not None: |
55 | | - dict_[attr_name] = attr_value |
56 | | - return dict_ |
57 | | - attrs["to_dict"] = to_dict |
| 70 | + # Convert dates to datetime objects. |
| 71 | + for date_attr_name in date_attributes: |
| 72 | + attr_value = getattr(self, date_attr_name) |
| 73 | + if attr_value and not isinstance(attr_value, datetime): |
| 74 | + date_as_datetime = ghdate_to_datetime(attr_value) |
| 75 | + setattr(self, date_attr_name, date_as_datetime) |
| 76 | + _contribute_method("__init__", constructor) |
| 77 | + |
| 78 | + def iterate(self): |
| 79 | + not_empty = lambda e: e is not None |
| 80 | + objdict = vars(self) |
| 81 | + for date_attr_name in date_attributes: |
| 82 | + date_value = objdict.get(date_attr_name) |
| 83 | + if date_value and isinstance(date_value, datetime): |
| 84 | + objdict[date_attr_name] = datetime_to_ghdate(date_value) |
| 85 | + |
| 86 | + return iter(filter(not_empty, objdict.items())) |
| 87 | + _contribute_method("__iter__", iterate) |
58 | 88 |
|
59 | 89 | return super_new(cls, name, bases, attrs) |
60 | 90 |
|
| 91 | + def contribute_method_to_cls(cls, name, func): |
| 92 | + func.func_name = name |
| 93 | + return func |
61 | 94 |
|
62 | 95 | class BaseData(object): |
63 | 96 | __metaclass__ = BaseDataType |
0 commit comments