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
|
import subprocess
import os
from os.path import join
import portage
from xml.etree.ElementTree import iterparse, ParseError
from django.db.transaction import commit_on_success
from django.core.management.color import color_style
from euscan.version import get_version_type
from djeuscan.processing import FakeLogger
from djeuscan.models import Package, Version, VersionLog, Category, Overlay
class ScanPortage(object):
def __init__(self, logger=None, no_log=False, purge_packages=False,
purge_versions=False, upstream=False):
self.logger = logger or FakeLogger()
self.no_log = no_log
self.purge_packages = purge_packages
self.purge_versions = purge_versions
self.upstream = upstream
self.style = color_style()
self._cache = {'packages': {}, 'versions': {}}
self._overlays = None
self._updated_packages = set()
def updated_packages(self):
return list(self._updated_packages)
def cache_hash_package(self, category, name):
return '%s/%s' % (category, name)
def cache_store_package(self, package):
key = self.cache_hash_package(package.category, package.name)
self._cache['packages'][key] = package
def cache_get_package(self, category, name):
return self._cache['packages'].get(
self.cache_hash_package(category, name)
)
def cache_hash_version(self, category, name, version, revision, slot,
overlay):
key = '%s/%s-%s-r%s %s %s' % (category, name,
version, revision,
slot, overlay)
return key
def cache_get_version(self, category, name, version, revision, slot,
overlay):
key = self.cache_hash_version(category, name, version, revision, slot,
overlay)
return self._cache['versions'].get(key)
def cache_store_version(self, version):
key = self.cache_hash_version(
version.package.category, version.package.name, version.version,
version.revision, version.slot, version.overlay
)
self._cache['versions'][key] = version
def scan_gentoopm(self, query, category=None):
import gentoopm
pm = gentoopm.get_package_manager()
if category:
packages = pm.stack.filter(key_category=category)
elif query:
packages = pm.stack.filter(query)
else:
packages = pm.stack
package = {}
package_name = None
for p in packages:
pkg = p.key.package
if pkg != package_name:
if package_name:
yield package
package_name = pkg
package['package'] = p.key.package
package['category'] = p.key.category
package['homepage'] = ' '.join(p.homepages)
package['description'] = p.description
package['versions'] = []
package['versions'].append(
(p._cpv, p.slot, p.repository or 'gentoo')
)
if package_name:
yield package
def scan_eix_xml(self, query, category=None):
cmd = ['eix', '--xml']
env = os.environ
env['XML_OVERLAY'] = 'true'
if query:
cmd.extend(['--exact', query])
if category:
cmd.extend(['-C', category])
sub = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE)
output = sub.stdout
try:
parser = iterparse(output, ["start", "end"])
parser.next() # read root tag just for testing output
except ParseError:
if query:
msg = "Unknown package '%s'" % query
else:
msg = "No packages."
self.logger.error(self.style.ERROR(msg))
return
package = {'versions': []}
category = ""
for event, elem in parser:
if event == "start": # on tag opening
if elem.tag == "category":
category = elem.attrib["name"]
elif elem.tag == "package":
package["package"] = elem.attrib["name"]
package["category"] = category
elif elem.tag in ["description", "homepage"]:
package[elem.tag] = elem.text or ""
elif elem.tag == "version":
# append version data to versions
cpv = "%s/%s-%s" % (
package["category"],
package["package"],
elem.attrib["id"]
)
slot = elem.attrib.get("slot", "0")
overlay = elem.attrib.get("repository", "gentoo")
overlay_path = elem.attrib.get("overlay", None)
package["versions"].append(
(cpv, slot, overlay, overlay_path)
)
elif event == "end": # on tag closing
if elem.tag == "package":
# clean old data
yield package
package = {"versions": []}
if elem.tag == "category":
# clean old data
category = ""
elem.clear()
def prepare_purge_versions(self, packages, query=None, category=None):
if not self.purge_versions:
return
# Set all versions dead, then set found versions alive and
# delete old versions
if not query:
# Optimisation for --all or --category
self.logger.info('Killing existing versions...')
qs = Version.objects.filter(packaged=True)
if category:
qs = qs.filter(package__category=category)
qs.update(alive=False)
self.logger.info('done')
else:
for package in packages:
Version.objects.filter(package=package, packaged=True).\
update(alive=False)
def scan(self, query=None, category=None):
if not query:
current_packages = Package.objects.all()
elif '/' in query:
cat, pkg = portage.catsplit(query)
current_packages = Package.objects.filter(category=cat, name=pkg)
else:
current_packages = Package.objects.filter(name=query)
if category:
current_packages = current_packages.filter(category=category)
self.prepare_purge_versions(current_packages, query, category)
packages_alive = set()
for data in self.scan_eix_xml(query, category):
#for data in self.scan_gentoopm(query, category):
cat, pkg = data['category'], data['package']
package = self.store_package(
cat, pkg, data['homepage'], data['description']
)
packages_alive.add("%s/%s" % (cat, pkg))
new_version = False
for cpv, slot, overlay, overlay_path in data['versions']:
obj, created = self.store_version(
package, cpv, slot, overlay, overlay_path
)
new_version = created or new_version
# If the package has at least one new version scan upstream for it
if new_version:
self._updated_packages.add(package)
self.purge_old_packages(current_packages, packages_alive)
self.purge_old_versions()
def store_package(self, cat, pkg, homepage, description):
created = False
obj = self.cache_get_package(cat, pkg)
if not obj:
obj, created = Package.objects.get_or_create(
category=cat,
name=pkg,
defaults={"homepage": homepage, "description": description},
)
self.cache_store_package(obj)
if created:
self.logger.info('+ [p] %s/%s' % (cat, pkg))
return obj
def store_version(self, package, cpv, slot, overlay, overlay_path):
cat, pkg, ver, rev = portage.catpkgsplit(cpv)
if not overlay:
overlay = 'gentoo'
created = False
obj = self.cache_get_version(
package.category, package.name, ver, rev, slot, overlay
)
overlay_path = overlay_path or portage.settings["PORTDIR"]
package_path = join(overlay_path, package.category, package.name)
ebuild_path = join(package_path, "%s.ebuild" % cpv.split("/")[-1])
metadata_path = join(package_path, "metadata.xml")
if not obj:
obj, created = Version.objects.get_or_create(
package=package, slot=slot,
revision=rev, version=ver,
overlay=overlay,
defaults={
"alive": True,
"packaged": True,
"vtype": get_version_type(ver),
"confidence": 100,
"handler": "portage",
"ebuild_path": ebuild_path,
"metadata_path": metadata_path,
}
)
if not created: # Created objects have defaults values
obj.alive = True
obj.packaged = True
obj.save()
if created:
self.cache_store_version(obj)
# nothing to do (note: it can't be an upstream version because
# overlay can't be empty here)
if not created:
return obj, created
# New version created
self.logger.info('+ [v] %s' % (obj))
if overlay == 'gentoo':
package.n_packaged += 1
else:
package.n_overlay += 1
package.n_versions += 1
package.save()
if not self.no_log:
VersionLog.objects.create(
package=obj.package,
action=VersionLog.VERSION_ADDED,
slot=obj.slot,
revision=obj.revision,
version=obj.version,
overlay=obj.overlay,
vtype=obj.vtype,
)
return obj, created
def purge_old_packages(self, packages, alive):
if not self.purge_packages:
return
for package in packages:
cp = "%s/%s" % (package.category, package.name)
if cp not in alive:
self.logger.info('- [p] %s' % (package))
package.delete()
def purge_old_versions(self):
if not self.purge_versions:
return
versions = Version.objects.filter(packaged=True, alive=False)
for version in versions:
if version.overlay == 'gentoo':
version.package.n_packaged -= 1
else:
version.package.n_overlay -= 1
version.package.n_versions -= 1
version.package.save()
self.logger.info('- [v] %s' % (version))
if self.no_log:
continue
VersionLog.objects.create(
package=version.package,
action=VersionLog.VERSION_REMOVED,
slot=version.slot,
revision=version.revision,
version=version.version,
overlay=version.overlay,
vtype=version.vtype,
)
versions.delete()
@commit_on_success
def scan_portage(packages=None, category=None, no_log=False, upstream=False,
purge_packages=False, purge_versions=False, prefetch=False,
logger=None):
logger = logger or FakeLogger()
if packages is None:
prefetch = True
scan_handler = ScanPortage(
logger=logger,
no_log=no_log,
purge_packages=purge_packages,
purge_versions=purge_versions
)
logger.info('Scanning portage tree...')
if prefetch:
logger.info('Prefetching objects...')
ppackages = Package.objects.all()
pversions = Version.objects.select_related('package').all()
if category:
ppackages = ppackages.filter(category=category)
pversions = pversions.filter(package__category=category)
for package in ppackages:
scan_handler.cache_store_package(package)
for version in pversions:
scan_handler.cache_store_version(version)
logger.info('done')
if not packages and category:
scan_handler.scan(category=category)
elif not packages:
scan_handler.scan()
else:
for pkg in packages:
if isinstance(pkg, Package):
scan_handler.scan('%s/%s' % (pkg.category, pkg.name))
else:
scan_handler.scan(pkg)
# Populate Category and Overlay
# TODO: - use portage.settings.categories()
# - read metadata.xml to add description
for cat in Package.objects.values('category').distinct():
obj, created = Category.objects.get_or_create(name=cat["category"])
if created:
logger.info("+ [c] %s", cat["category"])
# TODO: - get informations from layman and portage (path, url)
for overlay in Version.objects.values('overlay').distinct():
if not overlay["overlay"]:
continue
obj, created = Overlay.objects.get_or_create(name=overlay["overlay"])
if created:
logger.info("+ [o] %s", overlay["overlay"])
logger.info('Done.')
return scan_handler.updated_packages()
|