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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
|
# Copyright 2012, 2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from deform import Form
from deform import ValidationFailure
import json
import os
import pymongo
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from webob import Response
from charmworld import cached_view_config
from charmworld.forms.qa_assessment import get_qa_form_schema
from charmworld.forms.featured import CharmFeaturedness
from charmworld.models import (
Charm,
CharmFileSet,
CharmSource,
getfs,
find_charms,
QADataSource,
)
from charmworld.utils import quote_key
from charmworld.views import log
from charmworld.views import SANITIZE
from charmworld.views.api import API2
from charmworld.views.helpers import format_change
from charmworld.views.helpers import format_proof
from charmworld.views.helpers import found
from charmworld.views.helpers import interfaces
from charmworld.views.helpers import name_filter
from charmworld.views.helpers import sub_filter
class CharmDetail(Charm):
def __init__(self, charm_data):
super(CharmDetail, self).__init__(charm_data)
charm_data = self._representation
charm_data["d_requires"] = d_requires = []
requires = self.requires
if requires is None:
log.warning(
"charm with invalid requires %s", charm_data['branch_spec'])
requires = {}
for k, v in requires.items():
d = {"name": k, "interface": v["interface"]}
d_requires.append(d)
charm_data["d_provides"] = d_provides = []
for k, v in self.provides.items():
if isinstance(v, basestring):
interface = v
else:
interface = v['interface']
d = {"name": k, "interface": interface}
d_provides.append(d)
charm_data["d_config"] = d_config = []
if self.options:
for k, v in self.options.items():
d = {"name": k,
"default": v.get('default', u''),
'type': v.get('type', u''),
'description': v.get('description', u'')}
d_config.append(d)
charm_data['maintainer_name'] = name_filter(self.maintainer)
@property
def d_provides(self):
"""a list of interface dicts that the charm provides."""
return self._representation['d_provides']
@property
def d_requires(self):
"""a list of interface dicts that the charm requires."""
return self._representation['d_requires']
@property
def d_config(self):
"""a list of the charm's option dicts."""
return self._representation['d_config']
@property
def maintainer_name(self):
"""The name of the maintainer from the maintainer property."""
return self._representation['maintainer_name']
def _charm_readme(request, charm):
# Find a readme in the list of files for the charm.
for filedata in charm.files.values():
filename = filedata['filename']
if 'readme' in filename.lower():
# We've found a readme!
readme_extension = os.path.splitext(filename)[1][1:]
fs = getfs(request.db)
cfile = CharmFileSet.get_by_id(fs, filedata['fileid'])
return [readme_extension, unicode(cfile.read(), "utf8")]
else:
return [None, None]
def _charm_view(request, charm):
charm = CharmDetail(charm)
# Find the same package in other archives.
others = find_charms(request.db, {
"name": charm.name, "series": charm.series,
"branch_spec": {"$ne": charm.branch_spec}})
others = [Charm(other) for other in others]
readme_format, readme = _charm_readme(request, charm)
icon_path = None
if quote_key('icon.svg') in charm.files.keys():
remainder = API2._get_api_id(charm) + '/file/icon.svg'
# If we let the route_url do the work it'll escape the ~ in the charm
# id for the owner. We generate the base of Thee route via route_url,
# but then manually tack on the known 'good' reminder for the path to
# complete.
icon_path = request.route_path(
'api_2_single',
endpoint='charm'
)
icon_path = icon_path + '/' + remainder
qa_data_source = QADataSource.from_db(request.db)
return {
"charm": charm,
'format_change': format_change,
'format_proof': format_proof,
'icon_path': icon_path,
"name": charm.name,
"others": others,
"project": request.registry.settings.get('project_name', 'Not Set.'),
"qadata": qa_data_source.get_qa_data(charm),
"readme_format": readme_format,
"readme": readme,
}
def _config_view(charm):
return {"charm": Charm(charm), "onload": "prettyPrint()"}
def _hook_view(request, charm, hook):
fs = getfs(request.db)
fileid = CharmFileSet.gen_fileid(charm._representation, 'hooks/' + hook)
data = {
"project": request.registry.settings.get('project_name', 'Not Set.'),
"hook_raw": "Hook not found!",
"charm": charm,
"hook": hook,
"onload": "prettyPrint()"
}
if hook not in charm.files:
log.warning("Hook not found %s %s" % (charm.branch_spec, hook))
return data
else:
cfile = CharmFileSet.get_by_id(fs, fileid)
data['hook_raw'] = cfile.read()
return data
def _json_charm(charm):
charm_config = charm.config
charm = dict(charm._representation)
# Reformat config into old internal representation.
charm['config'] = charm_config
charm_keys = set(charm.keys())
for k in SANITIZE.intersection(charm_keys):
del charm[k]
return Response(
json.dumps(charm, indent=2),
headerlist=[
("Access-Control-Allow-Origin", "*"),
("Access-Control-Allow-Headers", "X-Requested-With")],
content_type=u"application/json")
def found_charm_collection(db, query, sub_only, only_promulgated=False):
"""Return a dict of found charms with subordinates flag.
Build a list of Charm objects for the found charm data. The list is
added to a dict (as charms) with a sub_only key to indicate if the
query is for subordinates only. The dict is compatible with the
charm-collection.pt template.
:param db: The database to query.
:param query: The query to match charms.
:param sub_only: Is the query restricted to subordinates?
:param only_promulgated: restrict the query to promulgated charms.
Default False.
:return: A dict {charms: [<Charm>], sub_only: sub_only}.
"""
collection_project = {
"name": 1, "owner": 1, "series": 1, "summary": 1, "short_url": 1}
collection_sort = [("name", pymongo.ASCENDING)]
results = found(find_charms(
db, query, collection_project,
sort=collection_sort, only_promulgated=only_promulgated))
charms = [Charm(charm_data) for charm_data in results]
return {"charms": charms, 'sub_only': sub_only}
@cached_view_config(
route_name="charm-collection",
renderer="charmworld:templates/charm-collection.pt")
def charm_collection(request):
query, sub_only = sub_filter({}, request)
return found_charm_collection(
request.db, query, sub_only, only_promulgated=True)
@cached_view_config(
route_name="personal-collection",
renderer="charmworld:templates/charm-collection.pt")
def personal_collection(request):
query, sub_only = sub_filter({
"owner": request.matchdict["owner"]
}, request)
return found_charm_collection(request.db, query, sub_only)
@cached_view_config(
route_name="series-collection",
renderer="charmworld:templates/charm-collection.pt")
def series_collection(request):
query, sub_only = sub_filter(
{"series": request.matchdict["series"]}, request)
return found_charm_collection(
request.db, query, sub_only, only_promulgated=True)
@cached_view_config(
route_name="personal-series",
renderer="charmworld:templates/charm-collection.pt")
def personal_series_collection(request):
query, sub_only = sub_filter(
{
"owner": request.matchdict["owner"],
"series": request.matchdict["series"]
},
request)
return found_charm_collection(request.db, query, sub_only)
def find_charm(request, promulgated=False):
spec = {
"name": request.matchdict['charm'],
"series": request.matchdict['series'],
}
if promulgated:
spec["promulgated"] = True
else:
spec["owner"] = request.matchdict['owner']
return found(request.db.charms.find_one(spec))
@cached_view_config(
route_name="personal-charm",
renderer="charmworld:templates/charm.pt")
def personal_charm(request):
return _charm_view(request, find_charm(request))
@cached_view_config(
route_name="personal-charm-revision-json")
@cached_view_config(
route_name="personal-charm-json")
def person_charm_json(request):
match = request.matchdict
if 'revision' in match and not match['revision'].isdigit():
match['charm'] = "%s-%s" % (
match['charm'], match['revision'])
charm = Charm(find_charm(request))
return _json_charm(charm)
@cached_view_config(
route_name="charm",
renderer="charmworld:templates/charm.pt")
def distro_charm(request):
return _charm_view(request, find_charm(request, promulgated=True))
@cached_view_config(
route_name="charm-revision-json",
)
@cached_view_config(
route_name="charm-json",
)
def distro_charm_json(request):
match = request.matchdict
if 'revision' in match and not match['revision'].isdigit():
match['charm'] = "%s-%s" % (
match['charm'], match['revision'])
charm = Charm(find_charm(request, promulgated=True))
return _json_charm(charm)
@cached_view_config(
route_name="hook",
renderer="charmworld:templates/hook.pt")
def hook(request):
charm = Charm(find_charm(request, promulgated=True))
return _hook_view(request, charm, request.matchdict["hook"])
@cached_view_config(
route_name="personal-hook",
renderer="charmworld:templates/hook.pt")
def personal_hook(request):
charm = Charm(find_charm(request))
return _hook_view(request, charm, request.matchdict["hook"])
@cached_view_config(
route_name="config",
renderer="charmworld:templates/config.pt")
def config(request):
return _config_view(find_charm(request, promulgated=True))
@cached_view_config(
route_name="personal-config",
renderer="charmworld:templates/config.pt")
def personal_config(request):
return _config_view(find_charm(request))
@cached_view_config(
route_name="interface-collection-map",
renderer="charmworld:templates/interface-collection.pt")
@cached_view_config(
route_name="interface-collection",
renderer="charmworld:templates/interface-collection-redux.pt")
def interface_collection(request):
return {
"interfaces": interfaces(request.db),
"project": request.registry.settings.get('project_name', 'Not Set.'),
}
@cached_view_config(
route_name="interface",
renderer="charmworld:templates/interface.pt")
def interface(request):
iface = request.matchdict["interface"]
return {
"interface": iface,
"providers": [
Charm(charm)
for charm in find_charms(request.db, {"i_provides": iface},
sort=[("name", pymongo.ASCENDING)])],
"requirers": [
Charm(charm)
for charm in find_charms(request.db, {"i_requires": iface},
sort=[("name", pymongo.ASCENDING)])]}
@view_config(
route_name="charm-qa-edit",
renderer='charmworld:templates/qa_edit.pt',
permission='edit',
)
def quality_edit(request):
valid_data = {}
charm = find_charm(request, promulgated=True)
qa_questions = request.db.qa.find()
schema = get_qa_form_schema(qa_questions)
qa_form = Form(schema, buttons=('submit',))
qa_form.css_class = 'form-horizontal well'
qa_data_source = QADataSource.from_db(request.db)
if 'submit' in request.POST:
data = request.POST.items()
try:
valid_data = qa_form.validate(data)
qa_data_source.save_qa_data(Charm(charm), valid_data)
form = qa_form.render(valid_data)
except ValidationFailure, exc:
qa_form = exc
valid_data = {}
form = qa_form.render()
else:
qa_data = qa_data_source.get_qa_data(Charm(charm)).charm_data
if qa_data is not None:
# There's existing data to use to fill the form with.
valid_data = qa_data
form = qa_form.render(valid_data)
return {
'charm': charm,
'form': form,
"values": valid_data,
}
@view_config(
route_name="charm-featured-edit",
renderer='charmworld:templates/qa_edit.pt',
permission='edit',
)
def featured_edit(request):
charm = find_charm(request, promulgated=True)
form = Form(CharmFeaturedness(), buttons=('submit',))
form.css_class = 'form-horizontal well'
if 'submit' in request.POST:
try:
data = request.POST.items()
valid_data = form.validate(data)
charm.update(valid_data)
CharmSource.from_request(request).save(charm)
series = request.matchdict['series']
name = request.matchdict['charm']
url = request.route_url('charm', series=series, charm=name)
return HTTPFound(url)
except ValidationFailure as form:
valid_data = {}
else:
valid_data = charm
return {
'charm': charm,
'form': form.render(valid_data),
"values": valid_data,
}
|