~jcsackett/charmworld/bac-tag-constraints

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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# Copyright 2012, 2013 Marco Ceppi, Canonical Ltd.  This software is
# licensed under the GNU Affero General Public License version 3 (see
# the file LICENSE).

"""

Maybe

- number of people in charmers / charm-contributors. [ push to launchpad]
- total number of external contributor charms (not including juju-core)

Implemented

X - show total commit activity on a weekly basis across the charm universe.[[
X - total number of charms (grouped by charm name)
X - total external contributor growth by week.

"""
import datetime
import itertools
import math
from models import Charm

DEFAULT_STEP = datetime.timedelta(7)
DEFAULT_START = datetime.datetime(year=2011, month=5, day=1)
JUJU_TEAM = [
    "castro", "byrum", "mims", "gandelman", "juan", "kapil", "mmm"]


class TimeSeries(object):

    _empty_value = 0

    def __init__(self, start_date, step, end_date=None):
        self._start_date = start_date
        if end_date is None:
            end_date = datetime.datetime.utcnow()
        self._end_date = end_date
        self._step = step
        self._series = {}
        self._initialize()

    def _initialize(self):
        # Fill the self._series dict with dates equally spaced from
        # _start_date to _end_date via _step units.  Those dates will be the
        # keys and the corresponding values will be the _empty_value.
        delta = self._end_date - self._start_date
        step_count = int(math.ceil(
            delta.total_seconds() / self._step.total_seconds()))
        value = self._empty_value
        for i in range(step_count):
            self._series[self._start_date + (self._step * i)] = value

    def _nearest(self, date):
        # Using "The Price is Right" rules.
        if isinstance(date, (int, float)):
            date = datetime.datetime.utcfromtimestamp(date)
        found = None
        for i in sorted(self._series):
            if date >= i and date < (i + self._step):
                found = i
                break
        return found

    def serialize(self):
        """Sorted tuple serialization."""
        items = self._series.items()
        items.sort()
        return items

    def records(self):
        """Serialized as a sorted list of dictionary records."""
        return {"series":
                [{"timespan": k.strftime("%m/%d/%y"),
                  "value": v} for k, v in self.serialize()]}


class CountTimeSeries(TimeSeries):

    def increment(self, date):
        key = self._nearest(date)
        if key:
            self._series[key] += 1


class AccumulatorTimeSeries(TimeSeries):

    def _initialize(self):
        super(AccumulatorTimeSeries, self)._initialize()
        self._values = set()

    def increment(self, date, value):
        if value in self._values:
            return
        self._values.add(value)
        self._increment_subsequent(date)

    def _increment_subsequent(self, date):
        key = self._nearest(date)
        if not key:
            return
        keys = self._series.keys()
        keys.sort()
        for k in keys[keys.index(key):]:
            self._series[k] += 1

    def records(self):
        records = super(AccumulatorTimeSeries, self).records()
        records["values"] = sorted(list(self._values))
        return records


class AccumulatorCategorySeries(TimeSeries):

    _empty_value = {}

    def __init__(self, start_date, step, end_date=None, keys=()):
        self._keys = keys
        super(AccumulatorCategorySeries, self).__init__(
            start_date, step, end_date)

    def _initialize(self):
        super(AccumulatorCategorySeries, self)._initialize()
        self._values = set()
        d = dict(zip(self._keys, itertools.repeat(0)))
        for k in self._series:
            self._series[k] = d.copy()

    def increment(self, date, value, category):
        if (value, category) in self._values:
            return
        self._values.add((value, category))
        self._increment_subsequent(date, category)

    def _increment_subsequent(self, date, category):
        key = self._nearest(date)
        if key is None:
            return
        keys = self._series.keys()
        keys.sort()
        for k in keys[keys.index(key):]:
            if category not in self._series[k]:
                self._series[k][category] = 0
            self._series[k][category] += 1

    def records(self):
        """Serialized as a sorted list of dictionary records."""
        records = []
        for k, v in self.serialize():
            record = {'timespan': k.strftime("%m/%d/%y")}
            for vkey in v.keys():
                record[vkey] = v[vkey]
            records.append(record)
        return {"series": records}


def categorize_contributor(committer):
    e_start = committer.find("<")
    e_end = committer.rfind(">")
    if e_start == -1 and not "@" in committer:
        return "community"
    email = committer[e_start + 1:e_end]
    address, domain = email.split("@")

    # Sigh...
    normalized = committer.lower()
    for m in JUJU_TEAM:
        if m in normalized:
            return "juju"

    if domain.startswith("ubuntu") or domain.startswith("canonical"):
        return "canonical"

    return "community"


def series_external_contributors(db, start=DEFAULT_START, step=DEFAULT_STEP):
    """Total number of community contributors by time slice.
    """
    # Caveats bzr identities are not stable but we use commits
    # as our best indicator of activity.
    series = AccumulatorTimeSeries(start, step)

    charms = [Charm(charm) for charm in db.charms.find()]

    for charm in charms:
        for change in charm.changes:
            team = False
            for m in JUJU_TEAM:
                if m in change['committer'].lower():
                    team = True
                    break
            if team:
                continue
            series.increment(change["created"], change['committer'])

    return series


def series_charm_authors(db, start=DEFAULT_START, step=DEFAULT_STEP):
    """Total number of community contributors by time slice.
    """
    # Caveats bzr identities are not stable but we use commits
    # as our best indicator of activity.
    series = AccumulatorCategorySeries(
        start, step, keys=('community', 'canonical', 'juju'))
    charms = [Charm(charm) for charm in db.charms.find()]

    # We need to process in date order to keep things stable
    # this should be a separate collection for queries/ordering
    # without memory loading the whole thing.
    changes = []
    for charm in charms:
        changes.extend(charm.changes)
    changes.sort(lambda x, y: cmp(x['created'], y['created']))
    for change in changes:
        series.increment(
            change['created'],
            change['committer'],
            categorize_contributor(change['committer']))

    return series


def series_charm_growth(db, start=DEFAULT_START, step=DEFAULT_STEP):
    """Total number of charms by time slice, collapses the namespace.
    """
    # Better to use Launchpad api to determine pushed branch creation.
    series = AccumulatorCategorySeries(start, step, keys=('distro', 'ppa'))
    charms = [Charm(charm) for charm in db.charms.find()]
    for charm in charms:
        if charm.changes:
            if charm.promulgated:
                series.increment(
                    charm.changes[-1]['created'], charm.name, "distro")
            else:
                series.increment(
                    charm.changes[-1]['created'], charm.name, "ppa")
    return series


def series_charm_changes(db, start=DEFAULT_START, step=DEFAULT_STEP):
    """Number of charm commits by time slice.
    """
    series = CountTimeSeries(start, step)

    charms = [Charm(charm) for charm in db.charms.find()]
    for charm in charms:
        for change in charm.changes:
            series.increment(change['created'])
    return series

if __name__ == '__main__':
    import pprint

    #print "Charm Change"
    #pprint.pprint(series_charm_changes().serialize())

    print "Charm Authors"
    series = series_charm_authors()
    #pprint.pprint(
    #committers = list(series._values)
    #pprint.pprint(zip(map(categorize_contributor, committers), committers))
    pprint.pprint(series.records())

    #print "Charm growth"
    #series = series_charm_growth()
    #pprint.pprint(series.records())