~launchpad-pqm/launchpad/devel

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
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""View support classes for the bazaar application."""

__metaclass__ = type

__all__ = [
    'BazaarApplicationView',
    'BazaarProductView',
    ]

from datetime import datetime

import bzrlib
from zope.component import getUtility

from canonical.config import config
from canonical.launchpad.webapp import (
    canonical_url,
    LaunchpadView,
    )
from canonical.launchpad.webapp.authorization import (
    precache_permission_for_objects,
    )
from lp.code.enums import CodeImportReviewStatus
from lp.code.interfaces.branch import (
    IBranchCloud,
    IBranchSet,
    )
from lp.code.interfaces.branchcollection import IAllBranches
from lp.code.interfaces.codeimport import ICodeImportSet
from lp.registry.interfaces.product import IProductSet
from lp.services.propertycache import cachedproperty


class BazaarApplicationView(LaunchpadView):

    page_title = 'Launchpad Branches'

    @property
    def branch_count(self):
        """Return the number of public branches."""
        return getUtility(IAllBranches).visibleByUser(None).count()

    @property
    def product_count(self):
        return getUtility(IProductSet).getProductsWithBranches().count()

    @property
    def import_count(self):
        return getUtility(ICodeImportSet).search(
            review_status=CodeImportReviewStatus.REVIEWED).count()

    @property
    def bzr_version(self):
        return bzrlib.__version__

    def _precacheViewPermissions(self, branches):
        """Precache the launchpad.View permissions on the branches."""
        # XXX: TimPenhey 2009-06-08 bug=324546
        # Until there is an API to do this nicely, shove the launchpad.view
        # permission into the request cache directly.
        precache_permission_for_objects(
            self.request, 'launchpad.View', branches)
        return branches

    @cachedproperty
    def recently_changed_branches(self):
        """Return the five most recently changed branches."""
        return self._precacheViewPermissions(
            list(getUtility(IBranchSet).getRecentlyChangedBranches(
                    5, visible_by_user=self.user)))

    @cachedproperty
    def recently_imported_branches(self):
        """Return the five most recently imported branches."""
        return self._precacheViewPermissions(
            list(getUtility(IBranchSet).getRecentlyImportedBranches(
                    5, visible_by_user=self.user)))

    @cachedproperty
    def recently_registered_branches(self):
        """Return the five most recently registered branches."""
        return self._precacheViewPermissions(
            list(getUtility(IBranchSet).getRecentlyRegisteredBranches(
                    5, visible_by_user=self.user)))

    @cachedproperty
    def short_product_tag_cloud(self):
        """Show a preview of the product tag cloud."""
        return BazaarProductView(None, None).products(
            num_products=config.launchpad.code_homepage_product_cloud_size)


class ProductInfo:

    def __init__(self, name, commits, author_count, size, elapsed):
        self.name = name
        self.url = '/' + name
        self.commits = commits
        self.author_count = author_count
        self.size = size
        self.elapsed_since_commit = elapsed

    @property
    def tag_class(self):
        return "cloud-size-%s" % self.size

    @property
    def time_darkness(self):
        if self.elapsed_since_commit is None:
            return "light"
        if self.elapsed_since_commit.days < 7:
            return "dark"
        if self.elapsed_since_commit.days < 14:
            return "medium"
        return "light"

    @property
    def html_class(self):
        return "%s cloud-%s" % (self.tag_class, self.time_darkness)

    @property
    def html_title(self):
        if self.commits == 1:
            size = "1 commit"
        else:
            size = "%d commits" % self.commits
        if self.author_count == 1:
            who = "1 person"
        else:
            who = "%s people" % self.author_count
        if self.elapsed_since_commit.days == 0:
            commit = "last commit less than a day old"
        elif self.elapsed_since_commit.days == 1:
            commit = "last commit one day old"
        else:
            commit = (
                "last commit %d days old" % self.elapsed_since_commit.days)
        return "%s by %s, %s" % (size, who, commit)


class BazaarProjectsRedirect(LaunchpadView):
    """Redirect the user to /projects on the code rootsite."""

    def initialize(self):
        # Redirect to the caller to the new location.
        product_set = getUtility(IProductSet)
        redirect_url = canonical_url(product_set, rootsite="code")
        # Moved permanently.
        self.request.response.redirect(redirect_url, status=301)


class BazaarProductView(LaunchpadView):
    """Browser class for products gettable with Bazaar."""

    page_title = 'Projects with active branches'

    def _make_distribution_map(self, values, percentile_map):
        """Given some values and a map of percentiles to other values, return
        a function that will take a value in the same domain as 'values' and
        map it to a value in the 'percentile_map' dict.

        There *must* be a percentile_map entry for 1.0.
        """
        def constrained_minimum(xs, a):
            """Return the smallest value of 'xs' strictly bigger than 'a'."""
            return min(x for x in xs if x > a)

        cutoffs = percentile_map.keys()
        num_values = float(len(values))
        value_to_cutoffs = {}
        for index, value in enumerate(values):
            cutoff = constrained_minimum(cutoffs, (index / num_values))
            value_to_cutoffs[value] = percentile_map[cutoff]
        if num_values > 0 and 1 in percentile_map:
            value_to_cutoffs[values[-1]] = percentile_map[1]
        return value_to_cutoffs

    def products(self, num_products=None):
        # The product_info ends up sorted on product name, as the product name
        # is the first item of the tuple returned, and is guaranteed to be
        # unique by the sql query.
        product_info = sorted(
            getUtility(IBranchCloud).getProductsWithInfo(num_products))
        if len(product_info) == 0:
            return
        now = datetime.today()
        counts = sorted(zip(*product_info)[1])
        size_mapping = {
            0.2: 'smallest',
            0.4: 'small',
            0.6: 'medium',
            0.8: 'large',
            1.0: 'largest',
            }
        num_commits_to_size = self._make_distribution_map(
            counts, size_mapping)

        for name, commits, author_count, last_revision_date in product_info:
            size = num_commits_to_size[commits]
            elapsed = now - last_revision_date
            yield ProductInfo(name, commits, author_count, size, elapsed)