forked from openSUSE/openSUSE-release-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pkglistgen.py
executable file
·1470 lines (1247 loc) · 58.1 KB
/
pkglistgen.py
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 SUSE LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# TODO: implement equivalent of namespace namespace:language(de) @SYSTEM
# TODO: solve all devel packages to include
from __future__ import print_function
import copy
from lxml import etree as ET
from collections import namedtuple
import sys
import cmdln
import logging
import urllib2
import filecmp
from osc.core import checkout_package
from osc.core import http_GET
from osc.core import makeurl
from osc.core import Package
from osc.core import show_results_meta
from osc.core import undelete_package
from osc import conf
from osclib.conf import Config, str2bool
from osclib.stagingapi import StagingAPI
from osclib.util import project_list_family
from osclib.util import project_list_family_prior
from xdg.BaseDirectory import save_cache_path
import glob
import hashlib
import io
import solv
from pprint import pprint, pformat
import os
import os.path
import subprocess
import re
import yaml
import requests
import urlparse
import gzip
import tempfile
import traceback
import random
import shutil
import string
import ToolBase
# share header cache with repochecker
from osclib.memoize import CACHEDIR
logger = logging.getLogger()
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
ARCHITECTURES = ['x86_64', 'ppc64le', 's390x', 'aarch64']
DEFAULT_REPOS = ("openSUSE:Factory/standard")
PRODUCT_SERVICE = '/usr/lib/obs/service/create_single_product'
class Group(object):
def __init__(self, name, pkglist):
self.name = name
self.safe_name = re.sub(r'\W', '_', name.lower())
self.pkglist = pkglist
self.architectures = pkglist.architectures
self.conditional = None
self.packages = dict()
self.locked = set()
self.solved_packages = None
self.solved = False
self.not_found = dict()
self.unresolvable = dict()
for a in ARCHITECTURES:
self.packages[a] = []
self.unresolvable[a] = dict()
self.comment = ' ### AUTOMATICALLY GENERATED, DO NOT EDIT ### '
self.srcpkgs = None
self.develpkgs = dict()
self.silents = set()
self.ignored = set()
# special feature for SLE. Patterns are marked for expansion
# of recommended packages, all others aren't. Only works
# with recommends on actual package names, not virtual
# provides.
self.expand_recommended = set()
pkglist.groups[self.safe_name] = self
def _add_to_packages(self, package, arch=None):
archs = self.architectures
if arch:
archs = [arch]
for a in archs:
self.packages[a].append([package, self.name])
def parse_yml(self, packages):
# package less group is a rare exception
if packages is None:
return
for package in packages:
if not isinstance(package, dict):
self._add_to_packages(package)
continue
name = package.keys()[0]
for rel in package[name]:
arch = None
if rel == 'locked':
self.locked.add(name)
continue
elif rel == 'silent':
self.silents.add(name)
elif rel == 'recommended':
self.expand_recommended.add(name)
else:
arch = rel
self._add_to_packages(name, arch)
def _verify_solved(self):
if not self.solved:
raise Exception('group {} not solved'.format(self.name))
def inherit(self, group):
for arch in self.architectures:
self.packages[arch] += group.packages[arch]
self.locked.update(group.locked)
self.silents.update(group.silents)
self.expand_recommended.update(group.expand_recommended)
# do not repeat packages
def ignore(self, without):
for arch in ['*'] + self.architectures:
s = set(without.solved_packages[arch].keys())
s |= set(without.solved_packages['*'].keys())
for p in s:
self.solved_packages[arch].pop(p, None)
for p in without.not_found.keys():
if not p in self.not_found:
continue
self.not_found[p] -= without.not_found[p]
if not self.not_found[p]:
self.not_found.pop(p)
for g in without.ignored:
self.ignore(g)
self.ignored.add(without)
def solve(self, ignore_recommended=False, include_suggested=False):
""" base: list of base groups or None """
solved = dict()
for arch in self.architectures:
solved[arch] = dict()
self.srcpkgs = dict()
self.recommends = dict()
self.suggested = dict()
for arch in self.architectures:
pool = self.pkglist._prepare_pool(arch)
# pool.set_debuglevel(10)
suggested = []
# packages resulting from explicit recommended expansion
extra = []
def solve_one_package(n, group):
jobs = list(self.pkglist.lockjobs[arch])
sel = pool.select(str(n), solv.Selection.SELECTION_NAME)
if sel.isempty():
logger.debug('{}.{}: package {} not found'.format(self.name, arch, n))
self.not_found.setdefault(n, set()).add(arch)
return
else:
if n in self.expand_recommended:
for s in sel.solvables():
for dep in s.lookup_deparray(solv.SOLVABLE_RECOMMENDS):
# only add recommends that exist as packages
rec = pool.select(dep.str(), solv.Selection.SELECTION_NAME)
if not rec.isempty():
extra.append([dep.str(), group + ":recommended:" + n])
jobs += sel.jobs(solv.Job.SOLVER_INSTALL)
locked = self.locked | self.pkglist.unwanted
for l in locked:
sel = pool.select(str(l), solv.Selection.SELECTION_NAME)
if sel.isempty():
# if we can't find it, it probably is not as important
logger.debug('{}.{}: locked package {} not found'.format(self.name, arch, l))
else:
jobs += sel.jobs(solv.Job.SOLVER_LOCK)
for s in self.silents:
sel = pool.select(str(s), solv.Selection.SELECTION_NAME | solv.Selection.SELECTION_FLAT)
if sel.isempty():
logger.warn('{}.{}: silent package {} not found'.format(self.name, arch, s))
else:
jobs += sel.jobs(solv.Job.SOLVER_INSTALL)
solver = pool.Solver()
if ignore_recommended:
solver.set_flag(solver.SOLVER_FLAG_IGNORE_RECOMMENDED, 1)
problems = solver.solve(jobs)
if problems:
for problem in problems:
msg = 'unresolvable: %s.%s: %s', self.name, arch, problem
if self.pkglist.ignore_broken:
logger.debug(msg)
else:
logger.debug(msg)
self.unresolvable[arch][n] = str(problem)
return
if hasattr(solver, 'get_recommended'):
for s in solver.get_recommended():
if s.name in locked:
continue
self.recommends.setdefault(s.name, group + ':' + n)
for s in solver.get_suggested():
suggested.append([s.name, group + ':suggested:' + n])
self.suggested.setdefault(s.name, group + ':' + n)
else:
logger.warn('newer libsolv needed for recommends!')
trans = solver.transaction()
if trans.isempty():
logger.error('%s.%s: nothing to do', self.name, arch)
return
for s in trans.newsolvables():
solved[arch].setdefault(s.name, group + ':' + n)
reason, rule = solver.describe_decision(s)
if None:
print(self.name, s.name, reason, rule.info().problemstr())
# don't ask me why, but that's how it seems to work
if s.lookup_void(solv.SOLVABLE_SOURCENAME):
src = s.name
else:
src = s.lookup_str(solv.SOLVABLE_SOURCENAME)
self.srcpkgs[src] = group + ':' + s.name
for n, group in self.packages[arch]:
solve_one_package(n, group)
if include_suggested:
seen = set()
while suggested:
n, group = suggested.pop()
if n in seen:
continue
seen.add(n)
solve_one_package(n, group)
common = None
# compute common packages across all architectures
for arch in self.architectures:
if common is None:
common = set(solved[arch].keys())
continue
common &= set(solved[arch].keys())
if common is None:
common = set()
# reduce arch specific set by common ones
solved['*'] = dict()
for arch in self.architectures:
for p in common:
solved['*'][p] = solved[arch].pop(p)
self.solved_packages = solved
self.solved = True
def check_dups(self, modules, overlap):
if not overlap:
return
packages = set(self.solved_packages['*'])
for arch in self.architectures:
packages.update(self.solved_packages[arch])
for m in modules:
# do not check with ourselves and only once for the rest
if m.name <= self.name:
continue
if self.name in m.conflicts or m.name in self.conflicts:
continue
mp = set(m.solved_packages['*'])
for arch in self.architectures:
mp.update(m.solved_packages[arch])
if len(packages & mp):
overlap.comment += '\n overlapping between ' + self.name + ' and ' + m.name
for p in sorted(packages & mp):
overlap.comment += '\n - ' + p
overlap._add_to_packages(p)
def collect_devel_packages(self):
for arch in self.architectures:
pool = self.pkglist._prepare_pool(arch)
sel = pool.Selection()
for s in pool.solvables_iter():
if s.name.endswith('-devel'):
# don't ask me why, but that's how it seems to work
if s.lookup_void(solv.SOLVABLE_SOURCENAME):
src = s.name
else:
src = s.lookup_str(solv.SOLVABLE_SOURCENAME)
if src in self.srcpkgs.keys():
self.develpkgs[s.name] = self.srcpkgs[src]
def _filter_already_selected(self, modules, pkgdict):
# erase our own - so we don't filter our own
for p in pkgdict.keys():
already_present = False
for m in modules:
for arch in ['*'] + self.architectures:
already_present = already_present or (p in m.solved_packages[arch])
if already_present:
del pkgdict[p]
def filter_already_selected(self, modules):
self._filter_already_selected(modules, self.recommends)
self._filter_already_selected(modules, self.suggested)
def toxml(self, arch, ignore_broken=False, comment=None):
packages = self.solved_packages[arch]
name = self.name
if arch != '*':
name += '.' + arch
root = ET.Element('group', {'name': name})
if comment:
c = ET.Comment(comment)
root.append(c)
if arch != '*':
cond = ET.SubElement(root, 'conditional', {
'name': 'only_{}'.format(arch)})
packagelist = ET.SubElement(
root, 'packagelist', {'relationship': 'recommends'})
missing = dict()
if arch == '*':
missing = self.not_found
unresolvable = self.unresolvable.get(arch, dict())
for name in sorted(packages.keys() + missing.keys() + unresolvable.keys()):
if name in self.silents:
continue
if name in missing:
msg = ' {} not found on {}'.format(name, ','.join(sorted(missing[name])))
if ignore_broken:
c = ET.Comment(msg)
packagelist.append(c)
continue
name = msg
if name in unresolvable:
msg = ' {} uninstallable: {}'.format(name, unresolvable[name])
if ignore_broken:
c = ET.Comment(msg)
packagelist.append(c)
continue
else:
logger.error(msg)
name = msg
status = self.pkglist.supportstatus(name)
attrs = {'name': name}
if status is not None:
attrs['supportstatus'] = status
p = ET.SubElement(packagelist, 'package', attrs)
if name in packages:
c = ET.Comment(' reason: {} '.format(packages[name]))
packagelist.append(c)
return root
def dump(self):
pprint({'name': self.name, 'missing': self.missing, 'packages': self.packages,
'solved': self.solved_packages, 'silents': self.silents})
return
archs = ['*'] + self.architectures
for arch in archs:
x = self.toxml(arch)
print(ET.tostring(x, pretty_print=True))
class PkgListGen(ToolBase.ToolBase):
def __init__(self):
ToolBase.ToolBase.__init__(self)
self.repos = DEFAULT_REPOS
# package -> supportatus
self.packages = dict()
self.default_support_status = 'l3'
self.groups = dict()
self._supportstatus = None
self.input_dir = '.'
self.output_dir = '.'
self.lockjobs = dict()
self.ignore_broken = False
self.ignore_recommended = False
self.include_suggested = False
self.unwanted = set()
self.output = None
self.locales = set()
def _dump_supportstatus(self):
for name in self.packages.keys():
for status in self.packages[name]:
if status == self.default_support_status:
continue
for group in self.packages[name][status]:
print(name, status)
def _load_supportstatus(self):
# XXX
fn = os.path.join(self.input_dir, 'supportstatus.txt')
self._supportstatus = dict()
if os.path.exists(fn):
with open(fn, 'r') as fh:
for l in fh:
# pkg, status
a = l.rstrip().split(' ')
if len(a) > 1:
self._supportstatus[a[0]] = a[1]
# TODO: make per product
def supportstatus(self, package):
if self._supportstatus is None:
self._load_supportstatus()
if package in self._supportstatus:
return self._supportstatus[package]
else:
return self.default_support_status
def _load_group_file(self, fn):
output = None
unwanted = None
with open(fn, 'r') as fh:
logger.debug("reading %s", fn)
for groupname, group in yaml.safe_load(fh).items():
if groupname == 'OUTPUT':
output = group
continue
if groupname == 'UNWANTED':
unwanted = set(group)
continue
g = Group(groupname, self)
g.parse_yml(group)
return output, unwanted
def load_all_groups(self):
for fn in glob.glob(os.path.join(self.input_dir, 'group*.yml')):
o, u = self._load_group_file(fn)
if o:
if self.output is not None:
raise Exception('OUTPUT defined multiple times')
self.output = o
if u:
self.unwanted |= u
def _write_all_groups(self):
self._check_supplements()
archs = ['*'] + self.architectures
for name in self.groups:
group = self.groups[name]
if not group.solved:
continue
fn = '{}.group'.format(group.name)
with open(os.path.join(self.output_dir, fn), 'w') as fh:
comment = group.comment
for arch in archs:
x = group.toxml(arch, self.ignore_broken, comment)
# only comment first time
comment = None
x = ET.tostring(x, pretty_print=True)
x = re.sub('\s*<!-- reason:', ' <!-- reason:', x)
# fh.write(ET.tostring(x, pretty_print = True, doctype = '<?xml version="1.0" encoding="UTF-8"?>'))
fh.write(x)
def _parse_product(self, root):
print(root.find('.//products/product/name').text)
for mnode in root.findall(".//mediasets/media"):
name = mnode.get('name')
print(' {}'.format(name))
for node in mnode.findall(".//use"):
print(' {}'.format(node.get('group')))
def list_products(self):
for fn in glob.glob('*.product'):
with open(os.path.join(self.input_dir, fn), 'r') as fh:
logger.debug("reading %s", fn)
root = ET.parse(fh).getroot()
self._parse_product(root)
def solve_module(self, groupname, includes, excludes):
g = self.groups[groupname]
for i in includes:
g.inherit(self.groups[i])
g.solve(self.ignore_recommended, self.include_suggested)
for e in excludes:
g.ignore(self.groups[e])
def _check_supplements(self):
tocheck = set()
for arch in self.architectures:
pool = self._prepare_pool(arch)
sel = pool.Selection()
for s in pool.solvables_iter():
sel.add_raw(solv.Job.SOLVER_SOLVABLE, s.id)
for s in sel.solvables():
for dep in s.lookup_deparray(solv.SOLVABLE_SUPPLEMENTS):
for d in dep.str().split(' '):
if d.startswith('namespace:modalias') or d.startswith('namespace:filesystem'):
tocheck.add(s.name)
all_grouped = set()
for g in self.groups.values():
if g.solved:
for arch in g.solved_packages.keys():
if g.solved_packages[arch]:
all_grouped.update(g.solved_packages[arch])
for p in tocheck - all_grouped:
logger.warn('package %s has supplements but is not grouped', p)
def _prepare_pool(self, arch):
pool = solv.Pool()
pool.setarch(arch)
self.lockjobs[arch] = []
solvables = set()
for prp in self.repos:
project, reponame = prp.split('/')
repo = pool.add_repo(project)
s = os.path.join(CACHEDIR, 'repo-{}-{}-{}.solv'.format(project, reponame, arch))
r = repo.add_solv(s)
if not r:
raise Exception("failed to add repo {}/{}/{}. Need to run update first?".format(project, reponame, arch))
for solvable in repo.solvables_iter():
if solvable.name in solvables:
self.lockjobs[arch].append(pool.Job(solv.Job.SOLVER_SOLVABLE | solv.Job.SOLVER_LOCK, solvable.id))
solvables.add(solvable.name)
pool.addfileprovides()
pool.createwhatprovides()
# https://github.com/openSUSE/libsolv/issues/231
if hasattr(pool, 'set_namespaceproviders'):
for l in self.locales:
pool.set_namespaceproviders(solv.NAMESPACE_LANGUAGE, pool.Dep(l), True)
else:
logger.warn('libsolv missing set_namespaceproviders()')
return pool
# parse file and merge all groups
def _parse_unneeded(self, filename):
filename = os.path.join(self.input_dir, filename)
if not os.path.isfile(filename):
return set()
fh = open(filename, 'r')
logger.debug("reading %s", filename)
result = set()
for groupname, group in yaml.safe_load(fh).items():
result.update(group)
return result
def _collect_unsorted_packages(self, modules):
uneeded_regexps = [re.compile(r)
for r in self._parse_unneeded('unneeded.yml')]
packages = dict()
for arch in self.architectures:
pool = self._prepare_pool(arch)
sel = pool.Selection()
archpacks = [s.name for s in pool.solvables_iter()]
for r in uneeded_regexps:
archpacks = [p for p in archpacks if not r.match(p)]
# convert to set
archpacks = set(archpacks) - self.unwanted
for g in modules:
for a in ('*', arch):
archpacks -= set(g.solved_packages[a].keys())
for package in archpacks:
packages.setdefault(package, []).append(arch)
with open(os.path.join(self.output_dir, 'unsorted.yml'), 'w') as fh:
fh.write("unsorted:\n")
for p in sorted(packages.keys()):
fh.write(" - ")
fh.write(p)
if len(packages[p]) != len(self.architectures):
fh.write(": [")
fh.write(','.join(sorted(packages[p])))
fh.write("]")
reason = self._find_reason(p, modules)
if reason:
fh.write(' # ' + reason)
fh.write(" \n")
# give a hint if the package is related to a group
def _find_reason(self, package, modules):
# go through the modules multiple times to find the "best"
for g in modules:
if package in g.recommends:
return 'recommended by ' + g.recommends[package]
for g in modules:
if package in g.suggested:
return 'suggested by ' + g.suggested[package]
for g in modules:
if package in g.develpkgs:
return 'devel package of ' + g.develpkgs[package]
return None
class CommandLineInterface(ToolBase.CommandLineInterface):
SCOPES = ['all', 'target', 'rings', 'staging', 'ports']
def __init__(self, *args, **kwargs):
ToolBase.CommandLineInterface.__init__(self, args, kwargs)
def get_optparser(self):
parser = ToolBase.CommandLineInterface.get_optparser(self)
parser.add_option('-r', '--repositories', dest='repos', metavar='REPOS', action='append',
help='repositories to process (%s)' % DEFAULT_REPOS)
parser.add_option('-i', '--input-dir', dest='input_dir', metavar='DIR',
help='input directory', default='.')
parser.add_option('-o', '--output-dir', dest='output_dir', metavar='DIR',
help='input directory', default='.')
parser.add_option('-a', '--architecture', dest='architectures', metavar='ARCH',
help='architecure', action='append')
parser.add_option('--default-support-status', dest='default_support_status', metavar='STATUS',
help='default support status', default=None)
return parser
def setup_tool(self):
tool = PkgListGen()
tool.input_dir = self.options.input_dir
tool.output_dir = self.options.output_dir
tool.default_support_status = self.options.default_support_status
if self.options.architectures:
tool.architectures = self.options.architectures
else:
tool.architectures = ARCHITECTURES
if self.options.repos:
repos = []
for r in self.options.repos:
# handle comas as well, easier for shell script for now
if ',' in r:
repos += r.split(',')
else:
repos.append(r)
tool.repos = repos
return tool
def do_list(self, subcmd, opts):
"""${cmd_name}: list all groups
${cmd_usage}
${cmd_option_list}
"""
self.tool.load_all_groups()
for name in sorted(self.tool.groups.keys()):
print(name)
# to be called only once to bootstrap
def do_dump_supportstatus(self, subcmd, opts):
"""${cmd_name}: dump supportstatus of input files
${cmd_usage}
${cmd_option_list}
"""
self.tool.load_all_groups()
self.tool._dump_supportstatus()
def do_list_products(self, subcmd, opts):
"""${cmd_name}: list all products
${cmd_usage}
${cmd_option_list}
"""
self.tool.list_products()
def do_update(self, subcmd, opts):
"""${cmd_name}: Solve groups
${cmd_usage}
${cmd_option_list}
"""
# only there to parse the repos
bs_mirrorfull = os.path.join(SCRIPT_PATH, 'bs_mirrorfull')
global_update = False
for prp in self.tool.repos:
project, repo = prp.split('/')
for arch in self.tool.architectures:
# TODO: refactor to common function with repo_checker.py
d = os.path.join(CACHEDIR, project, repo, arch)
if not os.path.exists(d):
os.makedirs(d)
logger.debug('updating %s', d)
args = [bs_mirrorfull]
args.append('--nodebug')
args.append('{}/public/build/{}/{}/{}'.format(self.tool.apiurl, project, repo, arch))
args.append(d)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
repo_update = False
for line in p.stdout:
logger.info(line.rstrip())
global_update = True
repo_update = True
solv_file = os.path.join(CACHEDIR, 'repo-{}-{}-{}.solv'.format(project, repo, arch))
if os.path.exists(solv_file) and not repo_update:
continue
files = [os.path.join(d, f)
for f in os.listdir(d) if f.endswith('.rpm')]
fh = open(solv_file, 'w')
p = subprocess.Popen(
['rpms2solv', '-m', '-', '-0'], stdin=subprocess.PIPE, stdout=fh)
p.communicate('\0'.join(files))
p.wait()
fh.close()
return global_update
def update_merge(self, nonfree):
"""Merge free and nonfree solv files or copy free to merged"""
for prp in self.tool.repos:
project, repo = prp.split('/')
for arch in self.tool.architectures:
solv_file = os.path.join(
CACHEDIR, 'repo-{}-{}-{}.solv'.format(project, repo, arch))
solv_file_merged = os.path.join(
CACHEDIR, 'repo-{}-{}-{}.merged.solv'.format(project, repo, arch))
if not nonfree:
shutil.copyfile(solv_file, solv_file_merged)
continue
solv_file_nonfree = os.path.join(
CACHEDIR, 'repo-{}-{}-{}.solv'.format(nonfree, repo, arch))
self.solv_merge(solv_file_merged, solv_file, solv_file_nonfree)
def solv_merge(self, solv_merged, *solvs):
solvs = list(solvs) # From tuple.
if os.path.exists(solv_merged):
modified = map(os.path.getmtime, [solv_merged] + solvs)
if max(modified) <= modified[0]:
# The two inputs were modified before or at the same as merged.
logger.debug('merge skipped for {}'.format(solv_merged))
return
with open(solv_merged, 'w') as handle:
p = subprocess.Popen(['mergesolv'] + solvs, stdout=handle)
p.communicate()
if p.returncode:
raise Exception('failed to create merged solv file')
def do_create_sle_weakremovers(self, subcmd, opts, *prjs):
for prj in prjs:
logger.debug("processing %s", prj)
self.options.repos = ['/'.join([prj, 'standard'])]
self.postoptparse()
opts.project = prj
self.do_update('update', opts)
drops = dict()
for arch in self.tool.architectures:
pool = solv.Pool()
pool.setarch(arch)
sysrepo = None
for prp in prjs:
fn = os.path.join(CACHEDIR, 'repo-{}-{}-{}.solv'.format(prp, 'standard', arch))
r = pool.add_repo(prp)
r.add_solv(fn)
if not sysrepo:
sysrepo = r
pool.createwhatprovides()
for s in pool.solvables_iter():
if s.repo == sysrepo or not (s.arch == 'noarch' or s.arch == arch):
continue
haveit = False
for s2 in pool.whatprovides(s.nameid):
if s2.repo == sysrepo and s.nameid == s2.nameid:
haveit = True
if haveit:
continue
nevr = pool.rel2id(s.nameid, s.evrid, solv.REL_EQ)
for s2 in pool.whatmatchesdep(solv.SOLVABLE_OBSOLETES, nevr):
if s2.repo == sysrepo:
continue
haveit = True
if haveit:
continue
if s.name not in drops:
drops[s.name] = {'repo': s.repo.name, 'archs': []}
if arch not in drops[s.name]['archs']:
drops[s.name]['archs'].append(arch)
for prp in prjs:
exclusives = dict()
print('#', prp)
for name in sorted(drops.keys()):
if drops[name]['repo'] != prp:
continue
if len(drops[name]['archs']) == len(self.tool.architectures):
print('Provides: weakremover({})'.format(name))
else:
jarch = ' '.join(sorted(drops[name]['archs']))
exclusives.setdefault(jarch, []).append(name)
for arch in sorted(exclusives.keys()):
print('%ifarch {}'.format(arch))
for name in sorted(exclusives[arch]):
print('Provides: weakremover({})'.format(name))
print('%endif')
def do_create_droplist(self, subcmd, opts, *oldsolv):
"""${cmd_name}: generate list of obsolete packages
The globally specified repositories are taken as the current
package set. All solv files specified on the command line
are old versions of those repos.
The command outputs all package names that are no longer
contained in or provided by the current repos.
${cmd_usage}
${cmd_option_list}
"""
drops = dict()
for arch in self.tool.architectures:
for old in oldsolv:
logger.debug("%s: processing %s", arch, old)
pool = solv.Pool()
pool.setarch(arch)
for prp in self.tool.repos:
project, repo = prp.split('/')
fn = os.path.join(CACHEDIR, 'repo-{}-{}-{}.solv'.format(project, repo, arch))
r = pool.add_repo(prp)
r.add_solv(fn)
sysrepo = pool.add_repo(os.path.basename(old).replace('.merged.solv', ''))
sysrepo.add_solv(old)
pool.createwhatprovides()
for s in sysrepo.solvables:
haveit = False
for s2 in pool.whatprovides(s.nameid):
if s2.repo == sysrepo or s.nameid != s2.nameid:
continue
haveit = True
if haveit:
continue
nevr = pool.rel2id(s.nameid, s.evrid, solv.REL_EQ)
for s2 in pool.whatmatchesdep(solv.SOLVABLE_OBSOLETES, nevr):
if s2.repo == sysrepo:
continue
haveit = True
if haveit:
continue
if s.name not in drops:
drops[s.name] = sysrepo.name
# mark it explicitly to avoid having 2 pools while GC is not run
del pool
ofh = sys.stdout
if self.options.output_dir:
name = os.path.join(self.options.output_dir, 'obsoletepackages.inc')
ofh = open(name, 'w')
for reponame in sorted(set(drops.values())):
print("<!-- %s -->" % reponame, file=ofh)
for p in sorted(drops):
if drops[p] != reponame:
continue
print(" <obsoletepackage>%s</obsoletepackage>" % p, file=ofh)
@cmdln.option('--overwrite', action='store_true', help='overwrite if output file exists')
def do_dump_solv(self, subcmd, opts, baseurl):
"""${cmd_name}: fetch repomd and dump solv
Dumps solv from published repository. Use solve to generate from
pre-published repository.
If an output directory is specified, a file named according
to the build is created there. Otherwise the solv file is
dumped to stdout.
${cmd_usage}
${cmd_option_list}
"""
name = None
ofh = sys.stdout
if self.options.output_dir:
build, repo_style = self.dump_solv_build(baseurl)
name = os.path.join(self.options.output_dir, '{}.solv'.format(build))
# For update repo name never changes so always update.
if not opts.overwrite and repo_style != 'update' and os.path.exists(name):
logger.info("%s exists", name)
return name
pool = solv.Pool()
pool.setarch()
repo = pool.add_repo(''.join(random.choice(string.letters) for _ in range(5)))
path_prefix = 'suse/' if name and repo_style == 'build' else ''
url = urlparse.urljoin(baseurl, path_prefix + 'repodata/repomd.xml')
repomd = requests.get(url)
ns = {'r': 'http://linux.duke.edu/metadata/repo'}
root = ET.fromstring(repomd.content)
primary_element = root.find('.//r:data[@type="primary"]', ns)
location = primary_element.find('r:location', ns).get('href')
sha256_expected = primary_element.find('r:checksum[@type="sha256"]', ns).text
# No build information in update repo to use repomd checksum in name.
if repo_style == 'update':
name = os.path.join(self.options.output_dir, '{}::{}.solv'.format(build, sha256_expected))
if not opts.overwrite and os.path.exists(name):
logger.info("%s exists", name)
return name
# Only consider latest update repo so remove old versions.
# Pre-release builds only make sense for non-update repos and once
# releases then only relevant for next product which does not
# consider pre-release from previous version.
for old_solv in glob.glob(os.path.join(self.options.output_dir, '{}::*.solv'.format(build))):
os.remove(old_solv)
f = tempfile.TemporaryFile()
f.write(repomd.content)
f.flush()
os.lseek(f.fileno(), 0, os.SEEK_SET)
repo.add_repomdxml(f, 0)
url = urlparse.urljoin(baseurl, path_prefix + location)
with requests.get(url, stream=True) as primary:
sha256 = hashlib.sha256(primary.content).hexdigest()
if sha256 != sha256_expected:
raise Exception('checksums do not match {} != {}'.format(sha256, sha256_expected))
content = gzip.GzipFile(fileobj=io.BytesIO(primary.content))
os.lseek(f.fileno(), 0, os.SEEK_SET)
f.write(content.read())
f.flush()
os.lseek(f.fileno(), 0, os.SEEK_SET)
repo.add_rpmmd(f, None, 0)
repo.create_stubs()
ofh = open(name + '.new', 'w')
repo.write(ofh)
if name is not None:
# Only update file if overwrite or different.
ofh.flush() # Ensure entirely written before comparing.
if not opts.overwrite and os.path.exists(name) and filecmp.cmp(name + '.new', name, shallow=False):