summaryrefslogtreecommitdiffstats
path: root/pykolab/xml/utils.py
blob: 35d7578896ff1dbc40398138dca603936ecf09c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import datetime
import pytz
import kolabformat
from dateutil.tz import tzlocal
from collections import OrderedDict


def to_dt(dt):
    """
        Convert a naive date or datetime to a tz-aware datetime.
    """

    if isinstance(dt, datetime.date) and not isinstance(dt, datetime.datetime) or dt is not None and not hasattr(dt, 'hour'):
        dt = datetime.datetime(dt.year, dt.month, dt.day, 0, 0, 0, 0, tzinfo=tzlocal())

    elif isinstance(dt, datetime.datetime):
        if dt.tzinfo == None:
            return dt.replace(tzinfo=pytz.utc)

    return dt


def from_cdatetime(_cdatetime, with_timezone=True):
    """
        Convert from kolabformat.cDateTime to datetime.date(time)
    """
    if not _cdatetime.isValid():
        return None

    (
        year,
        month,
        day,
    ) = (
        _cdatetime.year(),
        _cdatetime.month(),
        _cdatetime.day(),
    )

    if _cdatetime.hour() == None or _cdatetime.hour() < 0:
        return datetime.date(year, month, day)

    (
        hour,
        minute,
        second
    ) = (
        _cdatetime.hour(),
        _cdatetime.minute(),
        _cdatetime.second()
    )

    if with_timezone:
        _timezone = _cdatetime.timezone()

        if _timezone == '' or _timezone == None:
            _timezone = pytz.utc
        else:
            _timezone = pytz.timezone(_timezone)

        return datetime.datetime(year, month, day, hour, minute, second, tzinfo=_timezone)

    else:
        return datetime.datetime(year, month, day, hour, minute, second)


def to_cdatetime(_datetime, with_timezone=True, as_utc=False):
    """
        Convert a datetime.dateime object into a kolabformat.cDateTime instance
    """
    # convert date into UTC timezone
    if as_utc and hasattr(_datetime, "tzinfo"):
        if _datetime.tzinfo is not None:
            _datetime = _datetime.astimezone(pytz.utc)
        else:
            datetime = _datetime.replace(tzinfo=pytz.utc)
        with_timezone = False

    (
        year,
        month,
        day,
    ) = (
        _datetime.year,
        _datetime.month,
        _datetime.day,
    )

    if hasattr(_datetime, 'hour'):
        (
            hour,
            minute,
            second
        ) = (
            _datetime.hour,
            _datetime.minute,
            _datetime.second
        )
        _cdatetime = kolabformat.cDateTime(year, month, day, hour, minute, second)

    else:
        _cdatetime = kolabformat.cDateTime(year, month, day)

    if with_timezone and hasattr(_datetime, "tzinfo"):
        if _datetime.tzinfo.__str__() in ['UTC','GMT']:
            _cdatetime.setUTC(True)
        else:
            _cdatetime.setTimezone(_datetime.tzinfo.__str__())

    if as_utc:
        _cdatetime.setUTC(True)

    return _cdatetime


def compute_diff(a, b, reduced=False):
    """
        List the differences between two given dicts
    """
    diff = []

    properties = a.keys()
    properties.extend([x for x in b.keys() if x not in properties])

    for prop in properties:
        aa = a[prop] if a.has_key(prop) else None
        bb = b[prop] if b.has_key(prop) else None

        # compare two lists
        if isinstance(aa, list) or isinstance(bb, list):
            if not isinstance(aa, list):
                aa = [aa]
            if not isinstance(bb, list):
                bb = [bb]
            index = 0
            length = max(len(aa), len(bb))
            while index < length:
                aai = aa[index] if index < len(aa) else None
                bbi = bb[index] if index < len(bb) else None
                if not aai == bbi:
                    if reduced:
                        (old, new) = reduce_properties(aai, bbi)
                    else:
                        (old, new) = (aai, bbi)
                    diff.append(OrderedDict([('property', prop), ('index', index), ('old', old), ('new', new)]))
                index += 1

        # the two properties differ
        elif not aa.__class__ == bb.__class__ or not aa == bb:
            if reduced:
                (old, new) = reduce_properties(aa, bb)
            else:
                (old, new) = (aa, bb)
            diff.append(OrderedDict([('property', prop), ('old', old), ('new', new)]))

    return diff


def reduce_properties(aa, bb):
    """
        Compares two given structs and removes equal values in bb
    """
    if not isinstance(aa, dict) or not isinstance(bb, dict):
        return (aa, bb)

    properties = aa.keys()
    properties.extend([x for x in bb.keys() if x not in properties])

    for prop in properties:
        if not aa.has_key(prop) or not bb.has_key(prop):
            continue
        if isinstance(aa[prop], dict) and isinstance(bb[prop], dict):
            (aa[prop], bb[prop]) = reduce_properties(aa[prop], bb[prop])
        if aa[prop] == bb[prop]:
            # del aa[prop]
            del bb[prop]

    return (aa, bb)