-
Notifications
You must be signed in to change notification settings - Fork 0
/
repoquery.py
executable file
·1485 lines (1288 loc) · 53 KB
/
repoquery.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 -tt
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# (c) pmatilai@laiskiainen.org
import sys
sys.path.insert(0, '/usr/share/yum-cli')
import signal
import re
import fnmatch
import time
import os
import os.path
import exceptions
import urlparse
import operator
from optparse import OptionParser
from optparse import SUPPRESS_HELP
import logging
import yum
import yum.misc as misc
import yum.config
import yum.Errors
import yum.packages
from yum.i18n import to_unicode
from rpmUtils.arch import getArchList, getBaseArch
from rpmUtils.miscutils import formatRequire
import output
from urlgrabber.progress import TextMeter
from urlgrabber.progress import format_number
version = "0.0.11"
flags = { 'EQ':'=', 'LT':'<', 'LE':'<=', 'GT':'>', 'GE':'>=', 'None':' '}
std_qf = {
'nvr': '%{name}-%{version}-%{release}',
'nevra': '%{name}-%{epoch}:%{version}-%{release}.%{arch}',
'envra': '%{epoch}:%{name}-%{version}-%{release}.%{arch}',
'source': '%{sourcerpm}',
'info': """
Name : %{name}
Version : %{version}
Release : %{release}
Architecture: %{arch}
Size : %{installedsize}
Packager : %{packager}
Group : %{group}
URL : %{url}
Repository : %{repoid}
Summary : %{summary}
Source : %{sourcerpm}
Description :\n%{description}""",
}
querytags = [ 'name', 'version', 'release', 'epoch', 'arch', 'summary',
'description', 'packager', 'url', 'buildhost', 'sourcerpm',
'vendor', 'group', 'license', 'buildtime', 'filetime',
'installedsize', 'archivesize', 'packagesize', 'repoid',
'requires', 'provides', 'conflicts', 'obsoletes',
'relativepath', 'hdrstart', 'hdrend', 'id', 'buildorder',
]
def sec2isodate(timestr):
return time.strftime("%F %T", time.gmtime(int(timestr)))
def sec2date(timestr):
return to_unicode(time.ctime(int(timestr)))
def sec2day(timestr):
return to_unicode(time.strftime("%a %b %d %Y", time.gmtime(int(timestr))))
def _size2val(size, off, ui):
size = float(size)
off = 1024
if False: pass
elif size >= (off * 100):
return "%.0f%s" % ((size / off), ui)
elif size >= (off * 10):
return "%.1f%s" % ((size / off), ui)
return "%.2f%s" % ((size / off), ui)
def size2k(size):
return _size2val(size, 1024, " k")
def size2m(size):
return _size2val(size, 1024 * 1024, " M")
def size2g(size):
return _size2val(size, 1024 * 1024 * 1024, " G")
def size2t(size):
return _size2val(size, 1024 * 1024 * 1024 * 1024, " T")
def size2h(size):
return format_number(size)
convertmap = { 'date': sec2date,
'day': sec2day,
'isodate': sec2isodate,
'k': size2k,
'm': size2m,
'g': size2g,
'h': size2h,
}
class queryError(exceptions.Exception):
def __init__(self, value=None):
Exception.__init__(self)
self.value = value
def __str__(self):
return "%s" %(self.value,)
def __unicode__(self):
return '%s' % to_unicode(self.value)
class DotPlot(object):
def __init__(self):
print 'digraph packages {',
print """
size="20.69,25.52";
ratio="fill";
rankdir="TB";
orientation=port;
node[style="filled"];
outputorder="edgesfirst";
ranksep="1";
"""
def addPackage(self, pkg, deps):
# color calculations lifted from rpmgraph
h=0.5+(0.6/23*len(deps))
s=h+0.1
b=1.0
print '"%s" [color="%s %s %s"];' % (pkg, h, s, b)
print '"%s" -> {' % pkg
for req in deps:
print '"%s"' % req
print '} [color="%s %s %s"];\n' % (h, s, b)
def __del__(self):
print "}"
# abstract class
class pkgQuery:
"""
My implementation of __getitem__ either forwards to an implementation
of fmt_name), or to self.pkg.returnSimple(), allowing subclasses
to override the package's items.
@type pkg: L{yum.package.YumAvailablePackage}
@ivar qf: the query format for this package query
@type qf: str
"""
def __init__(self, pkg, qf, yb=None):
self.yb = yb
self.pkg = pkg
self.qf = qf
self.name = pkg.name
self.classname = None
self._translated_qf = {}
def __getitem__(self, item):
item = item.lower()
if hasattr(self, "fmt_%s" % item):
return getattr(self, "fmt_%s" % item)()
elif item.startswith('repo.'):
repo_item = item.split('.')[1]
try:
return getattr(self.pkg.repo, repo_item)
except AttributeError,e:
raise queryError("Invalid repo querytag '%s' for %s: %s" % (repo_item, self.classname, self.pkg))
elif hasattr(self.pkg, item):
return getattr(self.pkg, item)
res = None
convert = None
tmp = item.split(':')
if len(tmp) > 1:
item = tmp[0]
conv = tmp[1]
if conv in convertmap:
convert = convertmap[conv]
else:
raise queryError("Invalid conversion: %s" % conv)
# this construct is the way it is because pkg.licenses isn't
# populated before calling pkg.returnSimple() ?!
try:
res = self.pkg.returnSimple(item)
except (KeyError, ValueError):
if item == "license":
res = ", ".join(self.pkg.licenses)
else:
raise queryError("Invalid querytag '%s' for %s: %s" % (item, self.classname, self.pkg))
if convert:
res = convert(res)
return res
def __str__(self):
return self.fmt_queryformat()
def doQuery(self, method, *args, **kw):
if method in std_qf:
self.qf = std_qf[method]
return self.fmt_queryformat()
elif hasattr(self, "fmt_%s" % method):
return getattr(self, "fmt_%s" % method)(*args, **kw)
else:
raise queryError("Invalid package query: %s" % method)
def isSource(self):
return self["arch"] == "src"
def prco(self, what, **kw):
"""
Query for the provides/requires/conflicts/obsoletes of this package.
@param what: one of provides, requires, conflicts, obsoletes
@type what: str
@rtype: list of str
"""
# for subclasses to implement
raise NotImplementedError
def fmt_queryformat(self, **kw):
if not self.qf:
return self.fmt_nevra()
# Override .qf for fun and profit...
if self.qf not in self._translated_qf:
qf = self.qf
qf = qf.replace("\\n", "\n")
qf = qf.replace("\\t", "\t")
pattern = re.compile('%([-\d]*?){([:\.\w]*?)}')
fmt = re.sub(pattern, r'%(\2)\1s', qf)
self._translated_qf[self.qf] = fmt
return self._translated_qf[self.qf] % self
def fmt_requires(self, **kw):
if self.yb.options.output in ("ascii-tree", "dot-tree"):
self.fmt_tree_requires(output = self.yb.options.output,
tree_level = self.yb.options.tree_level,
dot = self.yb.options.dot)
else:
return "\n".join(self.prco('requires'))
def fmt_build_order(self, **kw):
return self.yb.build_order(self.name)
def fmt_provides(self, **kw):
return "\n".join(self.prco('provides'))
def fmt_conflicts(self, **kw):
if self.yb.options.output in ("ascii-tree", "dot-tree"):
self.fmt_tree_conflicts(output = self.yb.options.output,
tree_level = self.yb.options.tree_level,
dot = self.yb.options.dot)
else:
return "\n".join(self.prco('conflicts'))
def fmt_obsoletes(self, **kw):
if self.yb.options.output in ("ascii-tree", "dot-tree"):
self.fmt_tree_obsoletes(output = self.yb.options.output,
tree_level = self.yb.options.tree_level,
dot = self.yb.options.dot)
else:
return "\n".join(self.prco('obsoletes'))
def fmt_list(self, **kw):
return "\n".join(self.files())
def fmt_evr(self, **kw):
return "%(epoch)s:%(version)s-%(release)s" % self
def fmt_nevr(self, **kw):
return "%(name)s-%(evr)s" % self
def fmt_envr(self, **kw):
return "%(epoch)s:%(name)s-%(version)s-%(release)s" % self
def fmt_nevra(self, **kw):
return "%(nevr)s.%(arch)s" % self
def fmt_envra(self, **kw):
return "%(envr)s.%(arch)s" % self
def fmt_location(self, **kw):
loc = ''
repo = self.pkg.repo
if self['basepath']:
loc = "%(basepath)s/%(relativepath)s" % self
else:
repourl = repo.urls[0]
if repourl[-1] != '/':
repourl = repourl + '/'
loc = urlparse.urljoin(repourl, self['relativepath'])
return loc
def tree_print_req(self, req, val, level):
indent = ''
if level:
indent = ' | ' * (level - 1) + ' \_ '
print "%s%s [%s]" % (indent, str(req), str(val))
# These are common helpers for the --tree-* options...
@staticmethod
def _tree_print_req(req, val, level):
indent = ''
if level:
indent = ' | ' * (level - 1) + ' \_ '
print "%s%s [%s]" % (indent, str(req), str(val))
def _tree_pkg2uniq(self, pkg):
""" Turn a pkg into a "unique" req."""
if self.yb and self.yb.conf.showdupesfromrepos:
return str(pkg)
return "%s.%s" % (pkg.name, getBaseArch(pkg.arch))
def _tree_pkg2val(self, reqs, pkg):
reqs = sorted(reqs[self._tree_pkg2uniq(pkg)])
return str(len(reqs)) + ": " + ", ".join(reqs)
def _tree_maybe_add_pkg(self, all_reqs, loc_reqs, pkgs, pkg, val):
req = self._tree_pkg2uniq(pkg)
if req in loc_reqs:
loc_reqs[req].add(val)
return
if req in all_reqs:
pkgs[pkg] = None
loc_reqs[req] = set([val])
return
pkgs[pkg] = True
loc_reqs[req] = set([val])
all_reqs[req] = True
def _tree_maybe_add_pkgs(self, all_reqs, tups, tup2pkgs):
rpkgs = {}
loc_reqs = {}
for rptup in tups:
(rpn, rpf, (rp,rpv,rpr)) = rptup
if rpn.startswith('rpmlib'):
continue
rname = yum.misc.prco_tuple_to_string(rptup)
for npkg in sorted(tup2pkgs(rptup, rname), reverse=True):
self._tree_maybe_add_pkg(all_reqs, loc_reqs, rpkgs, npkg, rname)
return rpkgs, loc_reqs
def _fmt_tree_prov(self, prco_type, **kw):
pkg = kw.get('pkg', self.pkg)
req = kw.get('req', 'cmd line')
level = kw.get('level', 0)
all_reqs = kw.get('all_reqs', {})
if kw['output'].lower() == 'dot-tree':
if 'dot' not in kw.keys() or kw['dot'] is None:
kw['dot'] = DotPlot()
elif 'dot' not in kw.keys() or kw['dot'] is None:
kw['dot'] = None
if str(kw['tree_level']).lower() != 'all':
try:
kw['tree_level'] = int(kw['tree_level'])
except ValueError, er:
kw['tree_level'] = 'all'
if not 'output' in kw.keys():
kw['output'] = 'ascii-tree'
__req2pkgs = {}
def req2pkgs(ignore, req):
req = str(req)
if req in __req2pkgs:
return __req2pkgs[req]
if self.yb is None:
return []
yb = self.yb
providers = []
try:
# XXX rhbz#246519, for some reason returnPackagesByDep() fails
# to find some root level directories while
# searchPackageProvides() does... use that for now
matches = self.yb.searchPackageProvides([req])
if self.yb.options.pkgnarrow == 'repos':
# Sucks that we do the work, and throw it away...
for provider in matches:
if provider.repoid != 'installed':
providers.append(provider)
elif self.yb.options.pkgnarrow == 'installed':
# Sucks that we do the work, and throw it away...
for provider in matches:
if provider.repoid == 'installed':
providers.append(provider)
else:
# Assume "all"
providers = matches.keys()
except yum.Errors.YumBaseError, err:
print >>sys.stderr, "No package provides %s" % req
return []
__req2pkgs[req] = providers
return providers
dot = kw['dot']
tups = getattr(pkg, prco_type)
rpkgs, loc_reqs = self._tree_maybe_add_pkgs(all_reqs, tups, req2pkgs)
if dot is None:
self._tree_print_req(pkg, req, level)
lim = level + 1
else:
dot.addPackage(pkg, rpkgs)
lim = level + 2
nlevel = level + 1
if str(kw['tree_level']).lower() != 'all' and \
int(kw['tree_level']) < int(lim):
return
for rpkg in sorted(rpkgs):
if pkg.verEQ(rpkg):
continue
if rpkgs[rpkg] is None:
req = self._tree_pkg2val(loc_reqs, rpkg)
if dot is None:
self._tree_print_req(rpkg, req, nlevel)
continue
self._fmt_tree_prov(prco_type,
pkg = rpkg, level = nlevel, all_reqs = all_reqs,
req = self._tree_pkg2val(loc_reqs, rpkg),
tree_level = kw['tree_level'],
output = kw['output'],
dot = dot)
def fmt_tree_requires(self, **kw):
return self._fmt_tree_prov('requires', **kw)
def fmt_tree_conflicts(self, **kw):
return self._fmt_tree_prov('conflicts', **kw)
def fmt_tree_obsoletes(self, **kw):
pkg = kw.get('pkg', self.pkg)
level = kw.get('level', 0)
all_reqs = kw.get('all_reqs', {})
if kw['output'].lower() == 'dot-tree':
if 'dot' not in kw.keys() or kw['dot'] is None:
kw['dot'] = DotPlot()
elif 'dot' not in kw.keys() or kw['dot'] is None:
kw['dot'] = None
if str(kw['tree_level']).lower() != 'all':
try:
kw['tree_level'] = int(kw['tree_level'])
except ValueError, er:
kw['tree_level'] = 'all'
if not 'output' in kw.keys():
kw['output'] = 'ascii-tree'
def obs2pkgs():
if self.yb is None:
return []
yb = self.yb
obss = []
if self.yb.options.pkgnarrow in ('all', 'repos'):
for obs_n in pkg.obsoletes_names:
for opkg in yb.pkgSack.searchNevra(name=obs_n):
if opkg.obsoletedBy([pkg]):
obss.append(opkg)
if self.yb.options.pkgnarrow in ('all', 'installed'):
skip = set([opkg.pkgtup for opkg in obss])
for obs_n in pkg.obsoletes_names:
for opkg in yb.rpmdb.searchNevra(name=obs_n):
if opkg.pkgtup in skip:
continue
if opkg.obsoletedBy([pkg]):
obss.append(opkg)
return obss
dot = kw['dot']
if level:
reason = ''
else:
reason = 'cmd line'
rpkgs = obs2pkgs()
if dot is None:
self._tree_print_req(pkg, reason, level)
lim = level + 1
else:
dot.addPackage(pkg, rpkgs)
lim = level + 2
all_reqs[pkg] = None
nlevel = level + 1
if str(kw['tree_level']).lower() != 'all' and \
int(kw['tree_level']) < int(lim):
return
for rpkg in sorted(rpkgs):
if pkg.verEQ(rpkg):
continue
if rpkg in all_reqs and dot is None:
self._tree_print_req(rpkg, '', nlevel)
continue
self.fmt_tree_obsoletes(pkg=rpkg, level=nlevel, all_reqs=all_reqs,
tree_level = kw['tree_level'],
output = kw['output'],
dot = dot)
def fmt_tree_what_requires(self, **kw):
pkg = kw.get('pkg', self.pkg)
req = kw.get('req', 'cmd line')
level = kw.get('level', 0)
all_reqs = kw.get('all_reqs', {})
if kw['output'].lower() == 'dot-tree':
if 'dot' not in kw.keys() or kw['dot'] is None:
kw['dot'] = DotPlot()
if str(kw['tree_level']).lower() != 'all':
try:
kw['tree_level'] = int(kw['tree_level'])
except ValueError, er:
kw['tree_level'] = 'all'
if not 'output' in kw.keys():
kw['output'] = 'ascii-tree'
__prov2pkgs = {}
def prov2pkgs(prov, ignore):
if str(prov) in __prov2pkgs:
return __prov2pkgs[str(prov)]
if self.yb is None:
return []
yb = self.yb
arequirers = []
irequirers = []
try:
skip = {}
if yb.options.pkgnarrow in ('all', 'installed'):
irequirers = yb.rpmdb.getRequires(prov[0],prov[1],prov[2])
irequirers = irequirers.keys()
if yb.options.pkgnarrow in ('all', 'repos'):
areqs = yb.pkgSack.getRequires(prov[0],prov[1],prov[2])
if not irequirers:
arequirers = areqs.keys()
else:
skip = set([pkg.pkgtup for pkg in irequirers])
arequirers = [pkg for pkg in areqs
if pkg.pkgtup not in skip]
except yum.Errors.YumBaseError, err:
print >>sys.stderr, "No package provides %s" % str(prov)
return []
__prov2pkgs[str(prov)] = arequirers + irequirers
return arequirers + irequirers
filetupes = []
for n in pkg.filelist + pkg.dirlist + pkg.ghostlist:
filetupes.append((n, None, (None, None, None)))
tups = pkg.provides + filetupes
rpkgs, loc_reqs = self._tree_maybe_add_pkgs(all_reqs, tups, prov2pkgs)
dot = kw['dot']
if dot is None:
self._tree_print_req(pkg, req, level)
lim = level + 1
else:
dot.addPackage(pkg, rpkgs)
lim = level + 2
nlevel = level + 1
if str(kw['tree_level']).lower() != 'all' and \
int(kw['tree_level']) < int(lim):
return
for rpkg in sorted(rpkgs):
if pkg.verEQ(rpkg): # Remove deps. on self.
continue
if rpkgs[rpkg] is None:
req = self._tree_pkg2val(loc_reqs, rpkg)
if dot is None:
self._tree_print_req(rpkg, req, nlevel)
continue
self.fmt_tree_what_requires(pkg=rpkg,
level=nlevel, all_reqs=all_reqs,
req=self._tree_pkg2val(loc_reqs, rpkg),
tree_level = kw['tree_level'],
output = kw['output'],
dot = dot)
class repoPkgQuery(pkgQuery):
"""
I wrap a query of a non-installed package available in the repository.
"""
def __init__(self, pkg, qf, yb=None):
pkgQuery.__init__(self, pkg, qf, yb)
self.classname = 'repo pkg'
def prco(self, what, **kw):
rpdict = {}
#print(what)
for rptup in self.pkg.returnPrco(what):
(rpn, rpf, (rp,rpv,rpr)) = rptup
if rpn.startswith('rpmlib'):
continue
rpdict[misc.prco_tuple_to_string(rptup)] = None
rplist = rpdict.keys()
rplist.sort()
return rplist
def files(self, **kw):
fdict = {}
for ftype in self.pkg.returnFileTypes():
for fn in self.pkg.returnFileEntries(ftype):
# workaround for yum returning double leading slashes on some
# directories - posix allows that but it looks a bit odd
fdict[os.path.normpath('//%s' % fn)] = None
files = fdict.keys()
files.sort()
return files
def fmt_changelog(self, **kw):
changelog = []
for date, author, message in self.pkg.returnChangelog():
changelog.append("* %s %s\n%s\n" % (sec2day(date),
to_unicode(author),
to_unicode(message)))
return "\n".join(changelog)
class instPkgQuery(pkgQuery):
"""
I wrap a query of an installed package
of type L{yum.packages.YumInstalledPackage}
"""
# hmm, thought there'd be more things in need of mapping to rpm names :)
tagmap = { 'installedsize': 'size',
}
def __init__(self, pkg, qf, yb=None):
pkgQuery.__init__(self, pkg, qf, yb)
self.classname = 'installed pkg'
def __getitem__(self, item):
if item in self.tagmap:
return self.pkg.tagByName(self.tagmap[item])
elif item.startswith('yumdb_info.'):
yumdb_item = item.split('.')[1]
try:
return getattr(self.pkg.yumdb_info, yumdb_item)
except AttributeError,e:
raise queryError("Invalid yumdb querytag '%s' for %s: %s" % (yumdb_item, self.classname, self.pkg))
else:
return pkgQuery.__getitem__(self, item)
def prco(self, what, **kw):
prcodict = {}
# rpm names are without the trailing s :)
what = what[:-1]
names = self.pkg.tagByName('%sname' % what)
flags = self.pkg.tagByName('%sflags' % what)
ver = self.pkg.tagByName('%sversion' % what)
if names is not None:
for (n, f, v) in zip(names, flags, ver):
req = formatRequire(n, v, f)
# filter out rpmlib deps
if n.startswith('rpmlib'):
continue
prcodict[req] = None
prcolist = prcodict.keys()
prcolist.sort()
return prcolist
def files(self, **kw):
return self.pkg.tagByName('filenames')
def fmt_changelog(self, **kw):
changelog = []
times = self.pkg.tagByName('changelogtime')
if times is not None:
names = self.pkg.tagByName('changelogname')
texts = self.pkg.tagByName('changelogtext')
for date, author, message in zip(times, names, texts):
author = to_unicode(author)
message = to_unicode(message)
changelog.append("* %s %s\n%s\n" % (sec2day(date), author, message))
return "\n".join(changelog)
class groupQuery:
def __init__(self, group, grouppkgs="required"):
self.grouppkgs = grouppkgs
self.id = group.groupid
self.name = group.name
self.group = group
def doQuery(self, method, *args, **kw):
if hasattr(self, "fmt_%s" % method):
return "\n".join(getattr(self, "fmt_%s" % method)(*args, **kw))
else:
raise queryError("Invalid group query: %s" % method)
# XXX temporary hack to make --group -a query work
def fmt_queryformat(self, **kw):
return self.fmt_nevra()
def fmt_nevra(self, **kw):
return ["%s - %s" % (self.id, self.name)]
def fmt_list(self, **kw):
pkgs = []
for t in self.grouppkgs.split(','):
if t == "mandatory":
pkgs.extend(self.group.mandatory_packages)
elif t == "default":
pkgs.extend(self.group.default_packages)
elif t == "optional":
pkgs.extend(self.group.optional_packages)
elif t == "all":
pkgs.extend(self.group.packages)
else:
raise queryError("Unknown group package type %s" % t)
return pkgs
def fmt_requires(self, **kw):
return self.group.mandatory_packages
def fmt_info(self, **kw):
return ["%s:\n\n%s\n" % (self.name, self.group.description)]
class YumBaseQuery(yum.YumBase):
def __init__(self, pkgops = [], sackops = [], options = None):
"""
@type pkgops: list of str
@type sackops: list of str
@type options: L{optparse.Values}
"""
yum.YumBase.__init__(self)
self.logger = logging.getLogger("yum.verbose.repoquery")
console_stderr = logging.StreamHandler(sys.stderr)
console_stderr.setFormatter(logging.Formatter("%(message)s"))
self.logger.propagate = False
self.logger.addHandler(console_stderr)
self.options = options
self.pkgops = pkgops
self.sackops = sackops
self._sacks = []
if self.options.pkgnarrow in ('all', 'extras', 'installed'):
self._sacks.append('rpmdb')
if self.options.pkgnarrow not in ('extras', 'installed'):
self._sacks.append('pkgSack')
def queryPkgFactory(self, pkgs, plain_pkgs=False):
"""
For each given package, create a query.
@type pkgs: list of L{yum.package.YumAvailablePackage}
@rtype: list of L{queryPkg}
"""
qf = self.options.queryformat or std_qf["nevra"]
qpkgs = []
for pkg in pkgs:
if isinstance(pkg, yum.packages.YumInstalledPackage):
if self.options.pkgnarrow not in ('all', 'installed', 'extras'):
continue
if plain_pkgs:
qpkgs.append(pkg)
continue
if isinstance(pkg, yum.packages.YumInstalledPackage):
qpkg = instPkgQuery(pkg, qf, self)
else:
qpkg = repoPkgQuery(pkg, qf, self)
qpkgs.append(qpkg)
return qpkgs
def returnByName(self, name):
"""
Given a name, return a list of package queries matching the name.
@type name: str
@rtype: list of L{queryPkg}
"""
pkgs = []
try:
pkgs = self.returnPkgList(patterns=[name])
except yum.Errors.PackageSackError, err:
self.logger.error(err)
return self.queryPkgFactory(pkgs)
def returnPkgList(self, **kwargs):
pkgs = []
if 'patterns' in kwargs:
if len(kwargs['patterns']) == 1 and kwargs['patterns'][0] == '*':
kwargs['patterns'] = None
if self.options.pkgnarrow == "repos":
# self.pkgSack is a yum.packageSack.MetaSack
if self.conf.showdupesfromrepos:
pkgs = self.pkgSack.returnPackages(**kwargs)
else:
try:
pkgs = self.pkgSack.returnNewestByNameArch(**kwargs)
except yum.Errors.PackageSackError:
pkgs = []
else:
what = self.options.pkgnarrow
ygh = self.doPackageLists(what, **kwargs)
if what == "all":
pkgs = ygh.available + ygh.installed
elif hasattr(ygh, what):
pkgs = getattr(ygh, what)
else:
self.logger.error("Unknown pkgnarrow method: %s" % what)
return pkgs
def returnPackagesByDepStr(self, depstring):
provider = []
try:
# XXX rhbz#246519, for some reason returnPackagesByDep() fails
# to find some root level directories while
# searchPackageProvides() does... use that for now
matches = yum.YumBase.searchPackageProvides(self, [str(depstring)])
provider = matches.keys()
# provider.extend(yum.YumBase.returnPackagesByDep(self, depstring))
except yum.Errors.YumBaseError, err:
self.logger.error("No package provides %s" % depstring)
return self.queryPkgFactory(provider)
def returnGroups(self):
grps = []
for group in self.comps.get_groups():
grp = groupQuery(group, grouppkgs = self.options.grouppkgs)
grps.append(grp)
return grps
def matchGroups(self, items):
grps = []
for grp in self.returnGroups():
for expr in items:
if grp.name == expr or fnmatch.fnmatch("%s" % grp.name, expr):
grps.append(grp)
elif grp.id == expr or fnmatch.fnmatch("%s" % grp.id, expr):
grps.append(grp)
return grps
def matchPkgs(self, items, plain_pkgs=False):
pkgs = self.returnPkgList(patterns=items)
return self.queryPkgFactory(pkgs, plain_pkgs)
def matchSrcPkgs(self, items):
srpms = []
for name in items:
for pkg in self.returnByName(name):
if pkg.isSource():
continue
src = pkg["sourcerpm"][:-4]
srpms.extend(self.returnByName(src))
return srpms
def yum_search(self, terms):
"""use yum's search generator to search arbitrary fields"""
pkgs = []
fields = self.options.searchfields
if not fields:
fields = ['name', 'summary']
try:
matching = self.searchGenerator(fields, terms, searchtags=False)
for (po, matched_value) in matching:
if isinstance(po, yum.packages.YumInstalledPackage):
if self.options.pkgnarrow not in ('all', 'installed', 'extras'):
continue
if isinstance(po, yum.sqlitesack.YumAvailablePackageSqlite):
if self.options.pkgnarrow not in ('all', 'available', 'repos'):
continue
pkgs.append(po)
except (yum.Errors.RepoError,ValueError), e:
raise queryError("Could not run search: %s" % e)
return self.queryPkgFactory(pkgs)
def _at_grps(self, items):
# We want to move from @foo => lists of package names here, to make
# a bunch of things easier. Ie. pkgs. ops. on lists of packages from
# groups.
nitems = []
for item in items:
if item and item[0] == '@':
for grp in self.matchGroups([item[1:]]):
nitems.extend(grp.group.packages)
# Give warning when no matches?
continue
nitems.append(item)
return nitems
def runQuery(self, items):
plain_pkgs = False
if self.options.group:
pkgs = self.matchGroups(items)
elif self.options.groupmember:
pkglist = self.matchPkgs(items, plain_pkgs=True)
for pkg in sorted(pkglist):
print to_unicode(pkg)
for group in sorted(self.find_groupmember(pkg.name)):
print to_unicode(' @%s' % group)
pkgs = []
elif self.options.search:
plain_pkgs = False
pkgs = []
try:
pkgs = self.yum_search(items)
except queryError, e:
self.logger.error(e)
else:
items = self._at_grps(items)
if self.options.srpm:
pkgs = self.matchSrcPkgs(items)
else:
pkgs = []
if not self.sackops:
plain_pkgs = True
try:
pkgs = self.matchPkgs(items, plain_pkgs=plain_pkgs)
except yum.Errors.RepoError, e:
raise queryError("Could not match packages: %s" % to_unicode(e))
for prco in items:
for oper in self.sackops:
try:
for p in self.doQuery(oper, prco):
if p:
pkgs.append(p)
except queryError, e:
self.logger.error(e)
if plain_pkgs:
iq = None
rq = None
qf = self.options.queryformat or std_qf["nevra"]
pkgs = sorted(pkgs)
for pkg in pkgs:
if plain_pkgs:
if isinstance(pkg, yum.packages.YumInstalledPackage):
if iq is None:
iq = instPkgQuery(pkg, qf, self)
iq.pkg = pkg
iq.name = pkg.name
pkg = iq
else:
if rq is None:
rq = repoPkgQuery(pkg, qf, self)
rq.pkg = pkg
rq.name = pkg.name
pkg = rq
if not self.pkgops:
print to_unicode(pkg)
for oper in self.pkgops:
try:
out = pkg.doQuery(oper,
tree_level = self.options.tree_level,
output = self.options.output,
dot = self.options.dot)
if out:
print to_unicode(out)
except queryError, e:
self.logger.error(e)