forked from rpm-software-management/yum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.py
executable file
·3497 lines (3076 loc) · 136 KB
/
output.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 -t
"""Handle actual output from the cli."""
# 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.
# Copyright 2005 Duke University
import sys
import time
import logging
import types
import gettext
import pwd
import rpm
import re # For YumTerm
from weakref import proxy as weakref
from urlgrabber.progress import TextMeter, TextMultiFileMeter
import urlgrabber.progress
from urlgrabber.grabber import URLGrabError
from yum.misc import prco_tuple_to_string
from yum.i18n import to_str, to_utf8, to_unicode
import yum.misc
from rpmUtils.miscutils import checkSignals, formatRequire
from yum.constants import *
from yum import logginglevels, _, P_
from yum.rpmtrans import RPMBaseCallback
from yum.packageSack import packagesNewestByNameArch
import yum.packages
import yum.history
from yum.i18n import utf8_width, utf8_width_fill, utf8_text_fill
import locale
try:
assert max(2, 4) == 4
except:
# Python-2.4.x doesn't have min/max ... *sigh*
def min(x, *args):
for y in args:
if x > y: x = y
return x
def max(x, *args):
for y in args:
if x < y: x = y
return x
def _term_width():
""" Simple terminal width, limit to 20 chars. and make 0 == 80. """
if not hasattr(urlgrabber.progress, 'terminal_width_cached'):
return 80
ret = urlgrabber.progress.terminal_width_cached()
if ret == 0:
return 80
if ret < 20:
return 20
return ret
class YumTextMeter(TextMeter):
"""A class to display text progress bar output."""
def update(self, amount_read, now=None):
"""Update the status of the text progress bar
:param amount_read: the amount of data, in bytes, that has been read
:param now: the current time in seconds since the epoch. If
*now* is not given, the output of :func:`time.time()` will
be used.
"""
checkSignals()
TextMeter.update(self, amount_read, now)
class YumTextMultiFileMeter(TextMultiFileMeter):
def update_meter(self, meter, now):
checkSignals()
TextMultiFileMeter.update_meter(self, meter, now)
class YumTerm:
"""A class to provide some terminal "UI" helpers based on curses."""
# From initial search for "terminfo and python" got:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116
# ...it's probably not copyrightable, but if so ASPN says:
#
# Except where otherwise noted, recipes in the Python Cookbook are
# published under the Python license.
__enabled = True
if hasattr(urlgrabber.progress, 'terminal_width_cached'):
columns = property(lambda self: _term_width())
__cap_names = {
'underline' : 'smul',
'reverse' : 'rev',
'normal' : 'sgr0',
}
__colors = {
'black' : 0,
'blue' : 1,
'green' : 2,
'cyan' : 3,
'red' : 4,
'magenta' : 5,
'yellow' : 6,
'white' : 7
}
__ansi_colors = {
'black' : 0,
'red' : 1,
'green' : 2,
'yellow' : 3,
'blue' : 4,
'magenta' : 5,
'cyan' : 6,
'white' : 7
}
__ansi_forced_MODE = {
'bold' : '\x1b[1m',
'blink' : '\x1b[5m',
'dim' : '',
'reverse' : '\x1b[7m',
'underline' : '\x1b[4m',
'normal' : '\x1b(B\x1b[m'
}
__ansi_forced_FG_COLOR = {
'black' : '\x1b[30m',
'red' : '\x1b[31m',
'green' : '\x1b[32m',
'yellow' : '\x1b[33m',
'blue' : '\x1b[34m',
'magenta' : '\x1b[35m',
'cyan' : '\x1b[36m',
'white' : '\x1b[37m'
}
__ansi_forced_BG_COLOR = {
'black' : '\x1b[40m',
'red' : '\x1b[41m',
'green' : '\x1b[42m',
'yellow' : '\x1b[43m',
'blue' : '\x1b[44m',
'magenta' : '\x1b[45m',
'cyan' : '\x1b[46m',
'white' : '\x1b[47m'
}
def __forced_init(self):
self.MODE = self.__ansi_forced_MODE
self.FG_COLOR = self.__ansi_forced_FG_COLOR
self.BG_COLOR = self.__ansi_forced_BG_COLOR
def reinit(self, term_stream=None, color='auto'):
"""Reinitializes the :class:`YumTerm`.
:param term_stream: the terminal stream that the
:class:`YumTerm` should be initialized to use. If
*term_stream* is not given, :attr:`sys.stdout` is used.
:param color: when to colorize output. Valid values are
'always', 'auto', and 'never'. 'always' will use ANSI codes
to always colorize output, 'auto' will decide whether do
colorize depending on the terminal, and 'never' will never
colorize.
"""
self.__enabled = True
if not hasattr(urlgrabber.progress, 'terminal_width_cached'):
self.columns = 80
self.lines = 24
if color == 'always':
self.__forced_init()
return
# Output modes:
self.MODE = {
'bold' : '',
'blink' : '',
'dim' : '',
'reverse' : '',
'underline' : '',
'normal' : ''
}
# Colours
self.FG_COLOR = {
'black' : '',
'blue' : '',
'green' : '',
'cyan' : '',
'red' : '',
'magenta' : '',
'yellow' : '',
'white' : ''
}
self.BG_COLOR = {
'black' : '',
'blue' : '',
'green' : '',
'cyan' : '',
'red' : '',
'magenta' : '',
'yellow' : '',
'white' : ''
}
if color == 'never':
self.__enabled = False
return
assert color == 'auto'
# Curses isn't available on all platforms
try:
import curses
except:
self.__enabled = False
return
# If the stream isn't a tty, then assume it has no capabilities.
if not term_stream:
term_stream = sys.stdout
if not term_stream.isatty():
self.__enabled = False
return
# Check the terminal type. If we fail, then assume that the
# terminal has no capabilities.
try:
curses.setupterm(fd=term_stream.fileno())
except:
self.__enabled = False
return
self._ctigetstr = curses.tigetstr
if not hasattr(urlgrabber.progress, 'terminal_width_cached'):
self.columns = curses.tigetnum('cols')
self.lines = curses.tigetnum('lines')
# Look up string capabilities.
for cap_name in self.MODE:
mode = cap_name
if cap_name in self.__cap_names:
cap_name = self.__cap_names[cap_name]
self.MODE[mode] = self._tigetstr(cap_name) or ''
# Colors
set_fg = self._tigetstr('setf')
if set_fg:
for (color, val) in self.__colors.items():
self.FG_COLOR[color] = curses.tparm(set_fg, val) or ''
set_fg_ansi = self._tigetstr('setaf')
if set_fg_ansi:
for (color, val) in self.__ansi_colors.items():
self.FG_COLOR[color] = curses.tparm(set_fg_ansi, val) or ''
set_bg = self._tigetstr('setb')
if set_bg:
for (color, val) in self.__colors.items():
self.BG_COLOR[color] = curses.tparm(set_bg, val) or ''
set_bg_ansi = self._tigetstr('setab')
if set_bg_ansi:
for (color, val) in self.__ansi_colors.items():
self.BG_COLOR[color] = curses.tparm(set_bg_ansi, val) or ''
def __init__(self, term_stream=None, color='auto'):
self.reinit(term_stream, color)
def _tigetstr(self, cap_name):
# String capabilities can include "delays" of the form "$<2>".
# For any modern terminal, we should be able to just ignore
# these, so strip them out.
cap = self._ctigetstr(cap_name) or ''
return re.sub(r'\$<\d+>[/*]?', '', cap)
def sub(self, haystack, beg, end, needles, escape=None, ignore_case=False):
"""Search the string *haystack* for all occurrences of any
string in the list *needles*. Prefix each occurrence with
*beg*, and postfix each occurrence with *end*, then return the
modified string. For example::
>>> yt = YumTerm()
>>> yt.sub('spam and eggs', 'x', 'z', ['and'])
'spam xandz eggs'
This is particularly useful for emphasizing certain words
in output: for example, calling :func:`sub` with *beg* =
MODE['bold'] and *end* = MODE['normal'] will return a string
that when printed to the terminal will appear to be *haystack*
with each occurrence of the strings in *needles* in bold
face. Note, however, that the :func:`sub_mode`,
:func:`sub_bold`, :func:`sub_fg`, and :func:`sub_bg` methods
provide convenient ways to access this same emphasizing functionality.
:param haystack: the string to be modified
:param beg: the string to be prefixed onto matches
:param end: the string to be postfixed onto matches
:param needles: a list of strings to add the prefixes and
postfixes to
:param escape: a function that accepts a string and returns
the same string with problematic characters escaped. By
default, :func:`re.escape` is used.
:param ignore_case: whether case should be ignored when
searching for matches
:return: *haystack* with *beg* prefixing, and *end*
postfixing, occurrences of the strings in *needles*
"""
if not self.__enabled:
return haystack
if not escape:
escape = re.escape
render = lambda match: beg + match.group() + end
for needle in needles:
pat = escape(needle)
if ignore_case:
pat = re.template(pat, re.I)
haystack = re.sub(pat, render, haystack)
return haystack
def sub_norm(self, haystack, beg, needles, **kwds):
"""Search the string *haystack* for all occurrences of any
string in the list *needles*. Prefix each occurrence with
*beg*, and postfix each occurrence with self.MODE['normal'],
then return the modified string. If *beg* is an ANSI escape
code, such as given by self.MODE['bold'], this method will
return *haystack* with the formatting given by the code only
applied to the strings in *needles*.
:param haystack: the string to be modified
:param beg: the string to be prefixed onto matches
:param end: the string to be postfixed onto matches
:param needles: a list of strings to add the prefixes and
postfixes to
:return: *haystack* with *beg* prefixing, and self.MODE['normal']
postfixing, occurrences of the strings in *needles*
"""
return self.sub(haystack, beg, self.MODE['normal'], needles, **kwds)
def sub_mode(self, haystack, mode, needles, **kwds):
"""Search the string *haystack* for all occurrences of any
string in the list *needles*. Prefix each occurrence with
self.MODE[*mode*], and postfix each occurrence with
self.MODE['normal'], then return the modified string. This
will return a string that when printed to the terminal will
appear to be *haystack* with each occurrence of the strings in
*needles* in the given *mode*.
:param haystack: the string to be modified
:param mode: the mode to set the matches to be in. Valid
values are given by self.MODE.keys().
:param needles: a list of strings to add the prefixes and
postfixes to
:return: *haystack* with self.MODE[*mode*] prefixing, and
self.MODE['normal'] postfixing, occurrences of the strings
in *needles*
"""
return self.sub_norm(haystack, self.MODE[mode], needles, **kwds)
def sub_bold(self, haystack, needles, **kwds):
"""Search the string *haystack* for all occurrences of any
string in the list *needles*. Prefix each occurrence with
self.MODE['bold'], and postfix each occurrence with
self.MODE['normal'], then return the modified string. This
will return a string that when printed to the terminal will
appear to be *haystack* with each occurrence of the strings in
*needles* in bold face.
:param haystack: the string to be modified
:param needles: a list of strings to add the prefixes and
postfixes to
:return: *haystack* with self.MODE['bold'] prefixing, and
self.MODE['normal'] postfixing, occurrences of the strings
in *needles*
"""
return self.sub_mode(haystack, 'bold', needles, **kwds)
def sub_fg(self, haystack, color, needles, **kwds):
"""Search the string *haystack* for all occurrences of any
string in the list *needles*. Prefix each occurrence with
self.FG_COLOR[*color*], and postfix each occurrence with
self.MODE['normal'], then return the modified string. This
will return a string that when printed to the terminal will
appear to be *haystack* with each occurrence of the strings in
*needles* in the given color.
:param haystack: the string to be modified
:param color: the color to set the matches to be in. Valid
values are given by self.FG_COLOR.keys().
:param needles: a list of strings to add the prefixes and
postfixes to
:return: *haystack* with self.FG_COLOR[*color*] prefixing, and
self.MODE['normal'] postfixing, occurrences of the strings
in *needles*
"""
return self.sub_norm(haystack, self.FG_COLOR[color], needles, **kwds)
def sub_bg(self, haystack, color, needles, **kwds):
"""Search the string *haystack* for all occurrences of any
string in the list *needles*. Prefix each occurrence with
self.BG_COLOR[*color*], and postfix each occurrence with
self.MODE['normal'], then return the modified string. This
will return a string that when printed to the terminal will
appear to be *haystack* with each occurrence of the strings in
*needles* highlighted in the given background color.
:param haystack: the string to be modified
:param color: the background color to set the matches to be in. Valid
values are given by self.BG_COLOR.keys().
:param needles: a list of strings to add the prefixes and
postfixes to
:return: *haystack* with self.BG_COLOR[*color*] prefixing, and
self.MODE['normal'] postfixing, occurrences of the strings
in *needles*
"""
return self.sub_norm(haystack, self.BG_COLOR[color], needles, **kwds)
class YumOutput:
"""Main output class for the yum command line."""
def __init__(self):
self.logger = logging.getLogger("yum.cli")
self.verbose_logger = logging.getLogger("yum.verbose.cli")
if hasattr(rpm, "expandMacro"):
self.i18ndomains = rpm.expandMacro("%_i18ndomains").split(":")
else:
self.i18ndomains = ["redhat-dist"]
self.term = YumTerm()
self._last_interrupt = None
def printtime(self):
"""Return a string representing the current time in the form::
Mon dd hh:mm:ss
:return: a string representing the current time
"""
months = [_('Jan'), _('Feb'), _('Mar'), _('Apr'), _('May'), _('Jun'),
_('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec')]
now = time.localtime(time.time())
ret = months[int(time.strftime('%m', now)) - 1] + \
time.strftime(' %d %T ', now)
return ret
def failureReport(self, errobj):
"""Perform failure output for failovers from urlgrabber
:param errobj: :class:`urlgrabber.grabber.CallbackObject`
containing information about the error
:raises: *errobj*.exception
"""
self.logger.error('%s: %s', errobj.url, errobj.exception)
if hasattr(errobj, 'retry_no_cache') and errobj.retry_no_cache and \
errobj.exception.errno < 0:
self.logger.error(_('Trying again, now avoiding proxy cache.'))
# Raising an exception would cause urlgrabber to jump to the next
# mirror and what we want here is to retry with the same, so just
# return.
return
self.logger.error(_('Trying other mirror.'))
raise errobj.exception
def simpleProgressBar(self, current, total, name=None):
"""Output the current status to the terminal using a simple
status bar.
:param current: a number representing the amount of work
already done
:param total: a number representing the total amount of work
to be done
:param name: a name to label the progress bar with
"""
progressbar(current, total, name)
def _highlight(self, highlight):
hibeg = ''
hiend = ''
if not highlight:
pass
elif not isinstance(highlight, basestring) or highlight == 'bold':
hibeg = self.term.MODE['bold']
elif highlight == 'normal':
pass # Minor opt.
else:
# Turn a string into a specific output: colour, bold, etc.
for high in highlight.replace(',', ' ').split():
if False: pass
elif high == 'normal':
hibeg = ''
elif high in self.term.MODE:
hibeg += self.term.MODE[high]
elif high in self.term.FG_COLOR:
hibeg += self.term.FG_COLOR[high]
elif (high.startswith('fg:') and
high[3:] in self.term.FG_COLOR):
hibeg += self.term.FG_COLOR[high[3:]]
elif (high.startswith('bg:') and
high[3:] in self.term.BG_COLOR):
hibeg += self.term.BG_COLOR[high[3:]]
if hibeg:
hiend = self.term.MODE['normal']
return (hibeg, hiend)
def _sub_highlight(self, haystack, highlight, needles, **kwds):
hibeg, hiend = self._highlight(highlight)
return self.term.sub(haystack, hibeg, hiend, needles, **kwds)
@staticmethod
def _calc_columns_spaces_helps(current, data_tups, left):
""" Spaces left on the current field will help how many pkgs? """
ret = 0
for tup in data_tups:
if left < (tup[0] - current):
break
ret += tup[1]
return ret
def calcColumns(self, data, columns=None, remainder_column=0,
total_width=None, indent=''):
"""Dynamically calculate the widths of the columns that the
fields in data should be placed into for output.
:param data: a list of dictionaries that represent the data to
be output. Each dictionary in the list corresponds to a
column of output. The keys of the dictionary are the
lengths of the items to be output, and the value associated
with a key is the number of items of that length.
:param columns: a list containing the minimum amount of space
that must be allocated for each row. This can be used to
ensure that there is space available in a column if, for
example, the actual lengths of the items being output
cannot be given in *data*
:param remainder_column: number of the column to receive a few
extra spaces that may remain after other allocation has
taken place
:param total_width: the total width of the output.
self.term.columns is used by default
:param indent: string that will be prefixed to a line of
output to create e.g. an indent
:return: a list of the widths of the columns that the fields
in data should be placed into for output
"""
if total_width is None:
total_width = self.term.columns
cols = len(data)
# Convert the data to ascending list of tuples, (field_length, pkgs)
pdata = data
data = [None] * cols # Don't modify the passed in data
for d in range(0, cols):
data[d] = sorted(pdata[d].items())
# We start allocating 1 char to everything but the last column, and a
# space between each (again, except for the last column). Because
# at worst we are better with:
# |one two three|
# | four |
# ...than:
# |one two three|
# | f|
# |our |
# ...the later being what we get if we pre-allocate the last column, and
# thus. the space, due to "three" overflowing it's column by 2 chars.
if columns is None:
columns = [1] * (cols - 1)
columns.append(0)
total_width -= (sum(columns) + (cols - 1) + utf8_width(indent))
if not columns[-1]:
total_width += 1
while total_width > 0:
# Find which field all the spaces left will help best
helps = 0
val = 0
for d in xrange(0, cols):
thelps = self._calc_columns_spaces_helps(columns[d], data[d],
total_width)
if not thelps:
continue
# We prefer to overflow: the last column, and then earlier
# columns. This is so that in the best case (just overflow the
# last) ... grep still "works", and then we make it prettier.
if helps and (d == (cols - 1)) and (thelps / 2) < helps:
continue
if thelps < helps:
continue
helps = thelps
val = d
# If we found a column to expand, move up to the next level with
# that column and start again with any remaining space.
if helps:
diff = data[val].pop(0)[0] - columns[val]
if not columns[val] and (val == (cols - 1)):
# If we are going from 0 => N on the last column, take 1
# for the space before the column.
total_width -= 1
columns[val] += diff
total_width -= diff
continue
overflowed_columns = 0
for d in xrange(0, cols):
if not data[d]:
continue
overflowed_columns += 1
if overflowed_columns:
# Split the remaining spaces among each overflowed column
# equally
norm = total_width / overflowed_columns
for d in xrange(0, cols):
if not data[d]:
continue
columns[d] += norm
total_width -= norm
# Split the remaining spaces among each column equally, except the
# last one. And put the rest into the remainder column
cols -= 1
norm = total_width / cols
for d in xrange(0, cols):
columns[d] += norm
columns[remainder_column] += total_width - (cols * norm)
total_width = 0
return columns
@staticmethod
def _fmt_column_align_width(width):
if width < 0:
return (u"-", -width)
return (u"", width)
def _col_data(self, col_data):
assert len(col_data) == 2 or len(col_data) == 3
if len(col_data) == 2:
(val, width) = col_data
hibeg = hiend = ''
if len(col_data) == 3:
(val, width, highlight) = col_data
(hibeg, hiend) = self._highlight(highlight)
return (val, width, hibeg, hiend)
def fmtColumns(self, columns, msg=u'', end=u'', text_width=utf8_width):
"""Return a row of data formatted into a string for output.
Items can overflow their columns.
:param columns: a list of tuples containing the data to
output. Each tuple contains first the item to be output,
then the amount of space allocated for the column, and then
optionally a type of highlighting for the item
:param msg: a string to begin the line of output with
:param end: a string to end the line of output with
:param text_width: a function to find the width of the items
in the columns. This defaults to utf8 but can be changed
to len() if you know it'll be fine
:return: a row of data formatted into a string for output
"""
total_width = len(msg)
data = []
for col_data in columns[:-1]:
(val, width, hibeg, hiend) = self._col_data(col_data)
if not width: # Don't count this column, invisible text
msg += u"%s"
data.append(val)
continue
(align, width) = self._fmt_column_align_width(width)
val_width = text_width(val)
if val_width <= width:
# Don't use utf8_width_fill() because it sucks performance
# wise for 1,000s of rows. Also allows us to use len(), when
# we can.
msg += u"%s%s%s%s "
if (align == u'-'):
data.extend([hibeg, val, hiend, " " * (width - val_width)])
else:
data.extend([" " * (width - val_width), hibeg, val, hiend])
else:
msg += u"%s%s%s\n" + " " * (total_width + width + 1)
data.extend([hibeg, val, hiend])
total_width += width
total_width += 1
(val, width, hibeg, hiend) = self._col_data(columns[-1])
(align, width) = self._fmt_column_align_width(width)
val = utf8_width_fill(val, width, left=(align == u'-'),
prefix=hibeg, suffix=hiend)
msg += u"%%s%s" % end
data.append(val)
return msg % tuple(data)
def simpleList(self, pkg, ui_overflow=False, indent='', highlight=False,
columns=None):
"""Print a package as a line.
:param pkg: the package to be printed
:param ui_overflow: unused
:param indent: string to be prefixed onto the line to provide
e.g. an indent
:param highlight: highlighting options for the name of the
package
:param colums: tuple containing the space allocated for each
column of output. The columns are the package name, version,
and repository
"""
if columns is None:
columns = (-40, -22, -16) # Old default
ver = pkg.printVer()
na = '%s%s.%s' % (indent, pkg.name, pkg.arch)
hi_cols = [highlight, 'normal', 'normal']
rid = pkg.ui_from_repo
columns = zip((na, ver, rid), columns, hi_cols)
print self.fmtColumns(columns, text_width=len)
def simpleEnvraList(self, pkg, ui_overflow=False,
indent='', highlight=False, columns=None):
"""Print a package as a line, with the package itself in envra
format so it can be passed to list/install/etc.
:param pkg: the package to be printed
:param ui_overflow: unused
:param indent: string to be prefixed onto the line to provide
e.g. an indent
:param highlight: highlighting options for the name of the
package
:param colums: tuple containing the space allocated for each
column of output. The columns the are the package envra and
repository
"""
if columns is None:
columns = (-63, -16) # Old default
envra = '%s%s' % (indent, str(pkg))
hi_cols = [highlight, 'normal', 'normal']
rid = pkg.ui_from_repo
columns = zip((envra, rid), columns, hi_cols)
print self.fmtColumns(columns, text_width=len)
def fmtKeyValFill(self, key, val):
"""Return a key value pair in the common two column output
format.
:param key: the key to be formatted
:param val: the value associated with *key*
:return: the key value pair formatted in two columns for output
"""
val = to_str(val)
keylen = utf8_width(key)
cols = self.term.columns
nxt = ' ' * (keylen - 2) + ': '
ret = utf8_text_fill(val, width=cols,
initial_indent=key, subsequent_indent=nxt)
if ret.count("\n") > 1 and keylen > (cols / 3):
# If it's big, redo it again with a smaller subsequent off
ret = utf8_text_fill(val, width=cols,
initial_indent=key,
subsequent_indent=' ...: ')
return ret
def fmtSection(self, name, fill='='):
"""Format and return a section header. The format of the
header is a line with *name* centred, and *fill* repeated on
either side to fill an entire line on the terminal.
:param name: the name of the section
:param fill: the character to repeat on either side of *name*
to fill an entire line. *fill* must be a single character.
:return: a string formatted to be a section header
"""
name = to_str(name)
cols = self.term.columns - 2
name_len = utf8_width(name)
if name_len >= (cols - 4):
beg = end = fill * 2
else:
beg = fill * ((cols - name_len) / 2)
end = fill * (cols - name_len - len(beg))
return "%s %s %s" % (beg, name, end)
def _enc(self, s):
"""Get the translated version from specspo and ensure that
it's actually encoded in UTF-8."""
s = to_utf8(s)
if len(s) > 0:
for d in self.i18ndomains:
t = gettext.dgettext(d, s)
if t != s:
s = t
break
return to_unicode(s)
def infoOutput(self, pkg, highlight=False):
"""Print information about the given package.
:param pkg: the package to print information about
:param hightlight: highlighting options for the name of the
package
"""
(hibeg, hiend) = self._highlight(highlight)
print _("Name : %s%s%s") % (hibeg, to_unicode(pkg.name), hiend)
print _("Arch : %s") % to_unicode(pkg.arch)
if pkg.epoch != "0":
print _("Epoch : %s") % to_unicode(pkg.epoch)
print _("Version : %s") % to_unicode(pkg.version)
print _("Release : %s") % to_unicode(pkg.release)
print _("Size : %s") % self.format_number(float(pkg.size))
print _("Repo : %s") % to_unicode(pkg.repo.ui_id)
if pkg.repoid == 'installed' and 'from_repo' in pkg.yumdb_info:
print _("From repo : %s") % to_unicode(pkg.yumdb_info.from_repo)
if self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3):
print _("Committer : %s") % to_unicode(pkg.committer)
print _("Committime : %s") % time.ctime(pkg.committime)
print _("Buildtime : %s") % time.ctime(pkg.buildtime)
if hasattr(pkg, 'installtime'):
print _("Install time: %s") % time.ctime(pkg.installtime)
if pkg.repoid == 'installed':
uid = None
if 'installed_by' in pkg.yumdb_info:
try:
uid = int(pkg.yumdb_info.installed_by)
except ValueError: # In case int() fails
uid = None
print _("Installed by: %s") % self._pwd_ui_username(uid)
uid = None
if 'changed_by' in pkg.yumdb_info:
try:
uid = int(pkg.yumdb_info.changed_by)
except ValueError: # In case int() fails
uid = None
print _("Changed by : %s") % self._pwd_ui_username(uid)
print self.fmtKeyValFill(_("Summary : "), self._enc(pkg.summary))
if pkg.url:
print _("URL : %s") % to_unicode(pkg.url)
print self.fmtKeyValFill(_("License : "), to_unicode(pkg.license))
print self.fmtKeyValFill(_("Description : "),self._enc(pkg.description))
print ""
def updatesObsoletesList(self, uotup, changetype, columns=None, repoid=None):
"""Print a simple string that explains the relationship
between the members of an update or obsoletes tuple.
:param uotup: an update or obsoletes tuple. The first member
is the new package, and the second member is the old
package
:param changetype: a string indicating what the change between
the packages is, e.g. 'updates' or 'obsoletes'
:param columns: a tuple containing information about how to
format the columns of output. The absolute value of each
number in the tuple indicates how much space has been
allocated for the corresponding column. If the number is
negative, the text in the column will be left justified,
and if it is positive, the text will be right justified.
The columns of output are the package name, version, and repository
:param repoid: a repoid that the new package should belong to
"""
(changePkg, instPkg) = uotup
if repoid and changePkg.repoid != repoid:
return
if columns is not None:
# New style, output all info. for both old/new with old indented
chi = self.conf.color_update_remote
if changePkg.repo.id != 'installed' and changePkg.verifyLocalPkg():
chi = self.conf.color_update_local
self.simpleList(changePkg, columns=columns, highlight=chi)
self.simpleList(instPkg, columns=columns, indent=' ' * 4,
highlight=self.conf.color_update_installed)
return
# Old style
c_compact = changePkg.compactPrint()
i_compact = '%s.%s' % (instPkg.name, instPkg.arch)
c_repo = changePkg.repoid
print '%-35.35s [%.12s] %.10s %-20.20s' % (c_compact, c_repo, changetype, i_compact)
def listPkgs(self, lst, description, outputType, highlight_na={},
columns=None, highlight_modes={}):
"""Prints information about the given list of packages.
:param lst: a list of packages to print information about
:param description: string describing what the list of
packages contains, e.g. 'Available Packages'
:param outputType: The type of information to be printed.
Current options::
'list' - simple pkg list
'info' - similar to rpm -qi output
:param highlight_na: a dictionary containing information about
packages that should be highlighted in the output. The
dictionary keys are (name, arch) tuples for the package,
and the associated values are the package objects
themselves.
:param columns: a tuple containing information about how to
format the columns of output. The absolute value of each
number in the tuple indicates how much space has been
allocated for the corresponding column. If the number is
negative, the text in the column will be left justified,
and if it is positive, the text will be right justified.
The columns of output are the package name, version, and
repository
:param highlight_modes: dictionary containing information
about to highlight the packages in *highlight_na*.
*highlight_modes* should contain the following keys::
'not_in' - highlighting used for packages not in *highlight_na*
'=' - highlighting used when the package versions are equal
'<' - highlighting used when the package has a lower version number
'>' - highlighting used when the package has a higher version number
:return: (exit_code, [errors])
exit_code is::
0 = we're done, exit
1 = we've errored, exit with error string
"""
kern_pkgtup = yum.misc.get_running_kernel_pkgtup(self.ts)
if outputType in ['list', 'info']:
thingslisted = 0
if len(lst) > 0:
thingslisted = 1
print '%s' % description
for pkg in sorted(lst):
key = (pkg.name, pkg.arch)
highlight = False
if pkg.pkgtup == kern_pkgtup:
highlight = highlight_modes.get('kern','bold,underline')
elif key not in highlight_na:
highlight = highlight_modes.get('not in', 'normal')
elif pkg.verEQ(highlight_na[key]):
highlight = highlight_modes.get('=', 'normal')
elif pkg.verLT(highlight_na[key]):
highlight = highlight_modes.get('>', 'bold')
else:
highlight = highlight_modes.get('<', 'normal')
if outputType == 'list':
self.simpleList(pkg, ui_overflow=True,
highlight=highlight, columns=columns)
elif outputType == 'info':
self.infoOutput(pkg, highlight=highlight)
else:
pass
if thingslisted == 0:
return 1, ['No Packages to list']
return 0, []
def userconfirm(self, prompt=_('Is this ok [y/N]: '), extra={}):
"""Get a yes or no from the user, and default to No, and maybe more.
:param extra: a dict of ui responses to a list of their inputs.
:return: the UI response or None for no. At it's simplest this is 'yes' or None
"""
# Allow the one letter english versions in all langs.
yui = (u'y', to_unicode(_('y')), to_unicode(_('yes')))
nui = (u'n', to_unicode(_('n')), to_unicode(_('no')))
aui = set(yui + nui)
for xui in extra:
aui.update(extra[xui])
while True:
try:
choice = raw_input(prompt)
except UnicodeEncodeError:
raise
except UnicodeDecodeError:
raise
except:
choice = ''
choice = to_unicode(choice)
choice = choice.lower()
if len(choice) == 0 or choice in aui:
break
if not choice:
# Default, maybe configure this?