This file is indexed.

/usr/share/yum-cli/output.py is in yum 3.2.25-1ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
#!/usr/bin/python -t

"""This handles 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
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
from yum.constants import *

from yum import logginglevels, _
from yum.rpmtrans import RPMBaseCallback
from yum.packageSack import packagesNewestByNameArch
import yum.packages

from yum.i18n import utf8_width, utf8_width_fill, utf8_text_fill

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):

    """
    Text progress bar output.
    """

    def update(self, amount_read, now=None):
        checkSignals()
        TextMeter.update(self, amount_read, now)

class YumTerm:
    """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'):
        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):
        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):
        return self.sub(haystack, beg, self.MODE['normal'], needles, **kwds)

    def sub_mode(self, haystack, mode, needles, **kwds):
        return self.sub_norm(haystack, self.MODE[mode], needles, **kwds)

    def sub_bold(self, haystack, needles, **kwds):
        return self.sub_mode(haystack, 'bold', needles, **kwds)
    
    def sub_fg(self, haystack, color, needles, **kwds):
        return self.sub_norm(haystack, self.FG_COLOR[color], needles, **kwds)

    def sub_bg(self, haystack, color, needles, **kwds):
        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):
        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):
        """failure output for failovers from urlgrabber"""
        
        self.logger.error('%s: %s', errobj.url, errobj.exception)
        self.logger.error(_('Trying other mirror.'))
        raise errobj.exception
    
        
    def simpleProgressBar(self, current, total, name=None):
        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 width of the fields in the data, data is
            of the format [column-number][field_length] = rows. """

        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())

        if columns is None:
            columns = [1] * cols

        total_width -= (sum(columns) + (cols - 1) + utf8_width(indent))
        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
                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]
                columns[val] += diff
                total_width  -= diff
                continue

            #  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''):
        """ Return a string for columns of data, which can overflow."""

        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)
            if utf8_width(val) <= width:
                msg += u"%s "
                val = utf8_width_fill(val, width, left=(align == u'-'),
                                      prefix=hibeg, suffix=hiend)
                data.append(val)
            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):
        """ Simple to use function to print a pkg as a line. """

        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.repoid
        if pkg.repoid == 'installed' and 'from_repo' in pkg.yumdb_info:
            rid = '@' + pkg.yumdb_info.from_repo
        columns = zip((na, ver, rid), columns, hi_cols)
        print self.fmtColumns(columns)

    def simpleEnvraList(self, pkg, ui_overflow=False,
                        indent='', highlight=False, columns=None):
        """ Simple to use function to print a pkg as a line, with the pkg
            itself in envra format so it can be pased to list/install/etc. """

        if columns is None:
            columns = (-63, -16) # Old default
        envra = '%s%s' % (indent, str(pkg))
        hi_cols = [highlight, 'normal', 'normal']
        rid = pkg.repoid
        if pkg.repoid == 'installed' and 'from_repo' in pkg.yumdb_info:
            rid = '@' + pkg.yumdb_info.from_repo
        columns = zip((envra, rid), columns, hi_cols)
        print self.fmtColumns(columns)

    def fmtKeyValFill(self, key, val):
        """ Return a key value pair in the common two column output format. """
        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='='):
        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):
        (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.repoid)
        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 _("Installtime: %s") % time.ctime(pkg.installtime)
        print self.fmtKeyValFill(_("Summary    : "), self._enc(pkg.summary))
        if pkg.url:
            print _("URL        : %s") % to_unicode(pkg.url)
        print _("License    : %s") % to_unicode(pkg.license)
        print self.fmtKeyValFill(_("Description: "), self._enc(pkg.description))
        print ""
    
    def updatesObsoletesList(self, uotup, changetype, columns=None):
        """takes an updates or obsoletes tuple of pkgobjects and
           returns a simple printed string of the output and a string
           explaining the relationship between the tuple members"""
        (changePkg, instPkg) = uotup

        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={}):
        """outputs based on whatever outputType is. Current options:
           'list' - simple pkg list
           'info' - similar to rpm -qi output
           ...also highlight_na can be passed, and we'll highlight
           pkgs with (names, arch) in that set."""

        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 False: pass
                    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):
        """gets a yes or no from the user, defaults to No"""

        yui = (to_unicode(_('y')), to_unicode(_('yes')))
        nui = (to_unicode(_('n')), to_unicode(_('no')))
        aui = (yui[0], yui[1], nui[0], nui[1])
        while True:
            try:
                choice = raw_input(_('Is this ok [y/N]: '))
            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 the enlish one letter names don't mix, allow them too
            if u'y' not in aui and u'y' == choice:
                choice = yui[0]
                break
            if u'n' not in aui and u'n' == choice:
                break

        if len(choice) == 0 or choice not in yui:
            return False
        else:            
            return True
    
    def _cli_confirm_gpg_key_import(self, keydict):
        # FIXME what should we be printing here?
        return self.userconfirm()

    def _group_names2aipkgs(self, pkg_names):
        """ Convert pkg_names to installed pkgs or available pkgs, return
            value is a dict on pkg.name returning (apkg, ipkg). """
        ipkgs = self.rpmdb.searchNames(pkg_names)
        apkgs = self.pkgSack.searchNames(pkg_names)
        apkgs = packagesNewestByNameArch(apkgs)

        # This is somewhat similar to doPackageLists()
        pkgs = {}
        for pkg in ipkgs:
            pkgs[(pkg.name, pkg.arch)] = (None, pkg)
        for pkg in apkgs:
            key = (pkg.name, pkg.arch)
            if key not in pkgs:
                pkgs[(pkg.name, pkg.arch)] = (pkg, None)
            elif pkg.verGT(pkgs[key][1]):
                pkgs[(pkg.name, pkg.arch)] = (pkg, pkgs[key][1])

        # Convert (pkg.name, pkg.arch) to pkg.name dict
        ret = {}
        for (apkg, ipkg) in pkgs.itervalues():
            pkg = apkg or ipkg
            ret.setdefault(pkg.name, []).append((apkg, ipkg))
        return ret

    def _calcDataPkgColumns(self, data, pkg_names, pkg_names2pkgs,
                            indent='   '):
        for item in pkg_names:
            if item not in pkg_names2pkgs:
                continue
            for (apkg, ipkg) in pkg_names2pkgs[item]:
                pkg = ipkg or apkg
                envra = utf8_width(str(pkg)) + utf8_width(indent)
                if pkg.repoid == 'installed' and 'from_repo' in pkg.yumdb_info:
                    rid = len(pkg.yumdb_info.from_repo) + 1
                else:
                    rid   = len(pkg.repoid)
                for (d, v) in (('envra', envra), ('rid', rid)):
                    data[d].setdefault(v, 0)
                    data[d][v] += 1

    def _displayPkgsFromNames(self, pkg_names, verbose, pkg_names2pkgs,
                              indent='   ', columns=None):
        if not verbose:
            for item in sorted(pkg_names):
                print '%s%s' % (indent, item)
        else:
            for item in sorted(pkg_names):
                if item not in pkg_names2pkgs:
                    print '%s%s' % (indent, item)
                    continue
                for (apkg, ipkg) in sorted(pkg_names2pkgs[item],
                                           key=lambda x: x[1] or x[0]):
                    if ipkg and apkg:
                        highlight = self.conf.color_list_installed_older
                    elif apkg:
                        highlight = self.conf.color_list_available_install
                    else:
                        highlight = False
                    self.simpleEnvraList(ipkg or apkg, ui_overflow=True,
                                         indent=indent, highlight=highlight,
                                         columns=columns)
    
    def displayPkgsInGroups(self, group):
        print _('\nGroup: %s') % group.ui_name

        verb = self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3)
        if verb:
            print _(' Group-Id: %s') % to_unicode(group.groupid)
        pkg_names2pkgs = None
        if verb:
            pkg_names2pkgs = self._group_names2aipkgs(group.packages)
        if group.ui_description:
            print _(' Description: %s') % to_unicode(group.ui_description)

        sections = ((_(' Mandatory Packages:'),   group.mandatory_packages),
                    (_(' Default Packages:'),     group.default_packages),
                    (_(' Optional Packages:'),    group.optional_packages),
                    (_(' Conditional Packages:'), group.conditional_packages))
        columns = None
        if verb:
            data = {'envra' : {}, 'rid' : {}}
            for (section_name, pkg_names) in sections:
                self._calcDataPkgColumns(data, pkg_names, pkg_names2pkgs)
            data = [data['envra'], data['rid']]
            columns = self.calcColumns(data)
            columns = (-columns[0], -columns[1])

        for (section_name, pkg_names) in sections:
            if len(pkg_names) > 0:
                print section_name
                self._displayPkgsFromNames(pkg_names, verb, pkg_names2pkgs,
                                           columns=columns)

    def depListOutput(self, results):
        """take a list of findDeps results and 'pretty print' the output"""
        
        for pkg in results:
            print _("package: %s") % pkg.compactPrint()
            if len(results[pkg]) == 0:
                print _("  No dependencies for this package")
                continue

            for req in results[pkg]:
                reqlist = results[pkg][req] 
                print _("  dependency: %s") % prco_tuple_to_string(req)
                if not reqlist:
                    print _("   Unsatisfied dependency")
                    continue
                
                for po in reqlist:
                    print "   provider: %s" % po.compactPrint()

    def format_number(self, number, SI=0, space=' '):
        """Turn numbers into human-readable metric-like numbers"""
        symbols = ['',  # (none)
                    'k', # kilo
                    'M', # mega
                    'G', # giga
                    'T', # tera
                    'P', # peta
                    'E', # exa
                    'Z', # zetta
                    'Y'] # yotta
    
        if SI: step = 1000.0
        else: step = 1024.0
    
        thresh = 999
        depth = 0
        max_depth = len(symbols) - 1
    
        # we want numbers between 0 and thresh, but don't exceed the length
        # of our list.  In that event, the formatting will be screwed up,
        # but it'll still show the right number.
        while number > thresh and depth < max_depth:
            depth  = depth + 1
            number = number / step
    
        if type(number) == type(1) or type(number) == type(1L):
            format = '%i%s%s'
        elif number < 9.95:
            # must use 9.95 for proper sizing.  For example, 9.99 will be
            # rounded to 10.0 with the .1f format string (which is too long)
            format = '%.1f%s%s'
        else:
            format = '%.0f%s%s'
    
        return(format % (float(number or 0), space, symbols[depth]))

    @staticmethod
    def format_time(seconds, use_hours=0):
        return urlgrabber.progress.format_time(seconds, use_hours)

    def matchcallback(self, po, values, matchfor=None, verbose=None,
                      highlight=None):
        """ Output search/provides type callback matches. po is the pkg object,
            values are the things in the po that we've matched.
            If matchfor is passed, all the strings in that list will be
            highlighted within the output.
            verbose overrides logginglevel, if passed. """

        if self.conf.showdupesfromrepos:
            msg = '%s : ' % po
        else:
            msg = '%s.%s : ' % (po.name, po.arch)
        msg = self.fmtKeyValFill(msg, self._enc(po.summary))
        if matchfor:
            if highlight is None:
                highlight = self.conf.color_search_match
            msg = self._sub_highlight(msg, highlight, matchfor,ignore_case=True)
        
        print msg

        if verbose is None:
            verbose = self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3)
        if not verbose:
            return

        print _("Repo        : %s") % po.repoid
        print _('Matched from:')
        for item in yum.misc.unique(values):
            item = to_utf8(item)
            if to_utf8(po.name) == item or to_utf8(po.summary) == item:
                continue # Skip double name/summary printing

            can_overflow = True
            if False: pass
            elif to_utf8(po.description) == item:
                key = _("Description : ")
                item = self._enc(item)
            elif to_utf8(po.url) == item:
                key = _("URL         : %s")
                can_overflow = False
            elif to_utf8(po.license) == item:
                key = _("License     : %s")
                can_overflow = False
            elif item.startswith("/"):
                key = _("Filename    : %s")
                item = self._enc(item)
                can_overflow = False
            else:
                key = _("Other       : ")

            if matchfor:
                item = self._sub_highlight(item, highlight, matchfor,
                                           ignore_case=True)
            if can_overflow:
                print self.fmtKeyValFill(key, to_unicode(item))
            else:
                print key % item
        print '\n\n'

    def matchcallback_verbose(self, po, values, matchfor=None):
        return self.matchcallback(po, values, matchfor, verbose=True)
        
    def reportDownloadSize(self, packages):
        """Report the total download size for a set of packages"""
        totsize = 0
        locsize = 0
        error = False
        for pkg in packages:
            # Just to be on the safe side, if for some reason getting
            # the package size fails, log the error and don't report download
            # size
            try:
                size = int(pkg.size)
                totsize += size
                try:
                    if pkg.verifyLocalPkg():
                        locsize += size
                except:
                    pass
            except:
                error = True
                self.logger.error(_('There was an error calculating total download size'))
                break

        if (not error):
            if locsize:
                self.verbose_logger.log(logginglevels.INFO_1, _("Total size: %s"), 
                                        self.format_number(totsize))
            if locsize != totsize:
                self.verbose_logger.log(logginglevels.INFO_1, _("Total download size: %s"), 
                                        self.format_number(totsize - locsize))
            
    def listTransaction(self):
        """returns a string rep of the  transaction in an easy-to-read way."""
        
        self.tsInfo.makelists(True, True)
        pkglist_lines = []
        data  = {'n' : {}, 'v' : {}, 'r' : {}}
        a_wid = 0 # Arch can't get "that big" ... so always use the max.

        def _add_line(lines, data, a_wid, po, obsoletes=[]):
            (n,a,e,v,r) = po.pkgtup
            evr = po.printVer()
            repoid = po.repoid
            pkgsize = float(po.size)
            size = self.format_number(pkgsize)

            if a is None: # gpgkeys are weird
                a = 'noarch'

            # none, partial, full?
            if po.repo.id == 'installed':
                hi = self.conf.color_update_installed
            elif po.verifyLocalPkg():
                hi = self.conf.color_update_local
            else:
                hi = self.conf.color_update_remote
            lines.append((n, a, evr, repoid, size, obsoletes, hi))
            #  Create a dict of field_length => number of packages, for
            # each field.
            for (d, v) in (("n",len(n)), ("v",len(evr)), ("r",len(repoid))):
                data[d].setdefault(v, 0)
                data[d][v] += 1
            if a_wid < len(a): # max() is only in 2.5.z
                a_wid = len(a)
            return a_wid

        for (action, pkglist) in [(_('Installing'), self.tsInfo.installed),
                            (_('Updating'), self.tsInfo.updated),
                            (_('Removing'), self.tsInfo.removed),
                            (_('Reinstalling'), self.tsInfo.reinstalled),
                            (_('Downgrading'), self.tsInfo.downgraded),
                            (_('Installing for dependencies'), self.tsInfo.depinstalled),
                            (_('Updating for dependencies'), self.tsInfo.depupdated),
                            (_('Removing for dependencies'), self.tsInfo.depremoved)]:
            lines = []
            for txmbr in pkglist:
                a_wid = _add_line(lines, data, a_wid, txmbr.po, txmbr.obsoletes)

            pkglist_lines.append((action, lines))

        for (action, pkglist) in [(_('Skipped (dependency problems)'),
                                   self.skipped_packages),]:
            lines = []
            for po in pkglist:
                a_wid = _add_line(lines, data, a_wid, po)

            pkglist_lines.append((action, lines))

        if not data['n']:
            return u''
        else:
            data    = [data['n'],    {}, data['v'], data['r'], {}]
            columns = [1,         a_wid,         1,         1,  5]
            columns = self.calcColumns(data, indent="  ", columns=columns,
                                       remainder_column=2)
            (n_wid, a_wid, v_wid, r_wid, s_wid) = columns
            assert s_wid == 5

            out = [u"""
%s
%s
%s
""" % ('=' * self.term.columns,
       self.fmtColumns(((_('Package'), -n_wid), (_('Arch'), -a_wid),
                        (_('Version'), -v_wid), (_('Repository'), -r_wid),
                        (_('Size'), s_wid)), u" "),
       '=' * self.term.columns)]

        for (action, lines) in pkglist_lines:
            if lines:
                totalmsg = u"%s:\n" % action
            for (n, a, evr, repoid, size, obsoletes, hi) in lines:
                columns = ((n,   -n_wid, hi), (a,      -a_wid),
                           (evr, -v_wid), (repoid, -r_wid), (size, s_wid))
                msg = self.fmtColumns(columns, u" ", u"\n")
                hibeg, hiend = self._highlight(self.conf.color_update_installed)
                for obspo in obsoletes:
                    appended = _('     replacing  %s%s%s.%s %s\n\n')
                    appended %= (hibeg, obspo.name, hiend,
                                 obspo.arch, obspo.printVer())
                    msg = msg+appended
                totalmsg = totalmsg + msg
        
            if lines:
                out.append(totalmsg)

        summary = _("""
Transaction Summary
%s
""") % ('=' * self.term.columns,)
        out.append(summary)
        num_in = len(self.tsInfo.installed + self.tsInfo.depinstalled)
        num_up = len(self.tsInfo.updated + self.tsInfo.depupdated)
        summary = _("""\
Install   %5.5s Package(s)
Upgrade   %5.5s Package(s)
""") % (num_in, num_up,)
        if num_in or num_up: # Always do this?
            out.append(summary)
        num_rm = len(self.tsInfo.removed + self.tsInfo.depremoved)
        num_re = len(self.tsInfo.reinstalled)
        num_dg = len(self.tsInfo.downgraded)
        summary = _("""\
Remove    %5.5s Package(s)
Reinstall %5.5s Package(s)
Downgrade %5.5s Package(s)
""") % (num_rm, num_re, num_dg)
        if num_rm or num_re or num_dg:
            out.append(summary)
        
        return ''.join(out)
        
    def postTransactionOutput(self):
        out = ''
        
        self.tsInfo.makelists()

        #  Works a bit like calcColumns, but we never overflow a column we just
        # have a dynamic number of columns.
        def _fits_in_cols(msgs, num):
            """ Work out how many columns we can use to display stuff, in
                the post trans output. """
            if len(msgs) < num:
                return []

            left = self.term.columns - ((num - 1) + 2)
            if left <= 0:
                return []

            col_lens = [0] * num
            col = 0
            for msg in msgs:
                if len(msg) > col_lens[col]:
                    diff = (len(msg) - col_lens[col])
                    if left <= diff:
                        return []
                    left -= diff
                    col_lens[col] = len(msg)
                col += 1
                col %= len(col_lens)

            for col in range(len(col_lens)):
                col_lens[col] += left / num
                col_lens[col] *= -1
            return col_lens

        for (action, pkglist) in [(_('Removed'), self.tsInfo.removed), 
                                  (_('Dependency Removed'), self.tsInfo.depremoved),
                                  (_('Installed'), self.tsInfo.installed), 
                                  (_('Dependency Installed'), self.tsInfo.depinstalled),
                                  (_('Updated'), self.tsInfo.updated),
                                  (_('Dependency Updated'), self.tsInfo.depupdated),
                                  (_('Skipped (dependency problems)'), self.skipped_packages),
                                  (_('Replaced'), self.tsInfo.obsoleted),
                                  (_('Failed'), self.tsInfo.failed)]:
            msgs = []
            if len(pkglist) > 0:
                out += '\n%s:\n' % action
                for txmbr in pkglist:
                    (n,a,e,v,r) = txmbr.pkgtup
                    msg = "%s.%s %s:%s-%s" % (n,a,e,v,r)
                    msgs.append(msg)
                for num in (8, 7, 6, 5, 4, 3, 2):
                    cols = _fits_in_cols(msgs, num)
                    if cols:
                        break
                if not cols:
                    cols = [-(self.term.columns - 2)]
                while msgs:
                    current_msgs = msgs[:len(cols)]
                    out += '  '
                    out += self.fmtColumns(zip(current_msgs, cols), end=u'\n')
                    msgs = msgs[len(cols):]

        return out

    def setupProgressCallbacks(self):
        """sets up the progress callbacks and various 
           output bars based on debug level"""

        # if we're below 2 on the debug level we don't need to be outputting
        # progress bars - this is hacky - I'm open to other options
        # One of these is a download
        if self.conf.debuglevel < 2 or not sys.stdout.isatty():
            self.repos.setProgressBar(None)
            self.repos.callback = None
        else:
            self.repos.setProgressBar(YumTextMeter(fo=sys.stdout))
            self.repos.callback = CacheProgressCallback()

        # setup our failure report for failover
        freport = (self.failureReport,(),{})
        self.repos.setFailureCallback(freport)

        # setup callback for CTRL-C's
        self.repos.setInterruptCallback(self.interrupt_callback)
        
        # setup our depsolve progress callback
        dscb = DepSolveProgressCallBack(weakref(self))
        self.dsCallback = dscb
    
    def setupProgessCallbacks(self):
        # api purposes only to protect the typo
        self.setupProgressCallbacks()
    
    def setupKeyImportCallbacks(self):
        self.repos.confirm_func = self._cli_confirm_gpg_key_import
        self.repos.gpg_import_func = self.getKeyForRepo

    def interrupt_callback(self, cbobj):
        '''Handle CTRL-C's during downloads

        If a CTRL-C occurs a URLGrabError will be raised to push the download
        onto the next mirror.  
        
        If two CTRL-C's occur in quick succession then yum will exit.

        @param cbobj: urlgrabber callback obj
        '''
        delta_exit_chk = 2.0      # Delta between C-c's so we treat as exit
        delta_exit_str = _("two") # Human readable version of above

        now = time.time()

        if not self._last_interrupt:
            hibeg = self.term.MODE['bold']
            hiend = self.term.MODE['normal']
            # For translators: This is output like:
#  Current download cancelled, interrupt (ctrl-c) again within two seconds
# to exit.
            # Where "interupt (ctrl-c) again" and "two" are highlighted.
            msg = _("""
 Current download cancelled, %sinterrupt (ctrl-c) again%s within %s%s%s seconds
to exit.
""") % (hibeg, hiend, hibeg, delta_exit_str, hiend)
            self.verbose_logger.log(logginglevels.INFO_2, msg)
        elif now - self._last_interrupt < delta_exit_chk:
            # Two quick CTRL-C's, quit
            raise KeyboardInterrupt

        # Go to next mirror
        self._last_interrupt = now
        raise URLGrabError(15, _('user interrupt'))

    def download_callback_total_cb(self, remote_pkgs, remote_size,
                                   download_start_timestamp):
        if len(remote_pkgs) <= 1:
            return
        if not hasattr(urlgrabber.progress, 'TerminalLine'):
            return

        tl = urlgrabber.progress.TerminalLine(8)
        self.verbose_logger.log(logginglevels.INFO_2, "-" * tl.rest())
        dl_time = time.time() - download_start_timestamp
        if dl_time <= 0: # This stops divide by zero, among other problems
            dl_time = 0.01
        ui_size = tl.add(' | %5sB' % self.format_number(remote_size))
        ui_time = tl.add(' %9s' % self.format_time(dl_time))
        ui_end  = tl.add(' ' * 5)
        ui_bs   = tl.add(' %5sB/s' % self.format_number(remote_size / dl_time))
        msg = "%s%s%s%s%s" % (utf8_width_fill(_("Total"), tl.rest(), tl.rest()),
                              ui_bs, ui_size, ui_time, ui_end)
        self.verbose_logger.log(logginglevels.INFO_2, msg)

    def _history_uiactions(self, hpkgs):
        actions = set()
        count = 0
        for hpkg in hpkgs:
            st = hpkg.state
            if st == 'True-Install':
                st = 'Install'
            if st == 'Dep-Install': # Mask these at the higher levels
                st = 'Install'
            if st == 'Obsoleted': #  This is just a UI tweak, as we can't have
                                  # just one but we need to count them all.
                st = 'Obsoleting'
            if st in ('Install', 'Update', 'Erase', 'Reinstall', 'Downgrade',
                      'Obsoleting'):
                actions.add(st)
                count += 1
        assert len(actions) <= 6
        if len(actions) > 1:
            return count, ", ".join([x[0] for x in sorted(actions)])

        # So empty transactions work, although that "shouldn't" really happen
        return count, "".join(list(actions))

    def _pwd_ui_username(self, uid, limit=None):
        # loginuid is set to -1 on init.
        if uid is None or uid == 0xFFFFFFFF:
            loginid = _("<unset>")
            name = _("System") + " " + loginid
            if limit is not None and len(name) > limit:
                name = loginid
            return name

        try:
            user = pwd.getpwuid(uid)
            fullname = user.pw_gecos.split(';', 2)[0]
            name = "%s <%s>" % (fullname, user.pw_name)
            if limit is not None and len(name) > limit:
                name = "%s ... <%s>" % (fullname.split()[0], user.pw_name)
                if len(name) > limit:
                    name = "<%s>" % user.pw_name
            return name
        except KeyError:
            return str(uid)

    def _history_list_transactions(self, extcmds):
        tids = set()
        pats = []
        usertids = extcmds[1:]
        printall = False
        if usertids:
            printall = True
            if usertids[0] == 'all':
                usertids.pop(0)
        for tid in usertids:
            try:
                int(tid)
                tids.add(tid)
            except ValueError:
                pats.append(tid)
        if pats:
            tids.update(self.history.search(pats))

        if not tids and usertids:
            self.logger.critical(_('Bad transaction IDs, or package(s), given'))
            return None, None
        return tids, printall

    def historyListCmd(self, extcmds):
        """ Shows the user a list of data about the history. """

        tids, printall = self._history_list_transactions(extcmds)
        if tids is None:
            return 1, ['Failed history info']

        fmt = "%-6s | %-22s | %-16s | %-14s | %-7s"
        print fmt % ("ID", "Login user", "Date and time", "Action(s)","Altered")
        print "-" * 79
        fmt = "%6u | %-22.22s | %-16s | %-14s | %4u"
        done = 0
        limit = 20
        if printall:
            limit = None
        for old in self.history.old(tids, limit=limit):
            if not printall and done >= limit:
                break

            done += 1
            name = self._pwd_ui_username(old.loginuid, 22)
            tm = time.strftime("%Y-%m-%d %H:%M",
                               time.localtime(old.beg_timestamp))
            num, uiacts = self._history_uiactions(old.trans_data)
            if old.altered_lt_rpmdb and old.altered_gt_rpmdb:
                print fmt % (old.tid, name, tm, uiacts, num), "><"
            elif old.return_code is None:
                print fmt % (old.tid, name, tm, uiacts, num), "**"
            elif old.altered_lt_rpmdb:
                print fmt % (old.tid, name, tm, uiacts, num), " <"
            elif old.altered_gt_rpmdb:
                print fmt % (old.tid, name, tm, uiacts, num), "> "
            else:
                print fmt % (old.tid, name, tm, uiacts, num)
        lastdbv = self.history.last()
        if lastdbv is not None:
            #  If this is the last transaction, is good and it doesn't
            # match the current rpmdb ... then mark it as bad.
            rpmdbv  = self.rpmdb.simpleVersion(main_only=True)[0]
            if lastdbv.end_rpmdbversion != rpmdbv:
                errstring = _('Warning: RPMDB has been altered since the last yum transaction.')
                self.logger.warning(errstring)

    def _history_get_transactions(self, extcmds):
        if len(extcmds) < 2:
            self.logger.critical(_('No transaction ID given'))
            return None

        tids = []
        try:
            int(extcmds[1])
            tids.append(extcmds[1])
        except ValueError:
            self.logger.critical(_('Bad transaction ID given'))
            return None

        old = self.history.old(tids)
        if not old:
            self.logger.critical(_('Not found given transaction ID'))
            return None
        return old
    def _history_get_transaction(self, extcmds):
        old = self._history_get_transactions(extcmds)
        if old is None:
            return None
        if len(old) > 1:
            self.logger.critical(_('Found more than one transaction ID!'))
        return old[0]

    def historyInfoCmd(self, extcmds):
        tids = set()
        pats = []
        for tid in extcmds[1:]:
            try:
                int(tid)
                tids.add(tid)
            except ValueError:
                pats.append(tid)
        if pats:
            tids.update(self.history.search(pats))

        if not tids and len(extcmds) < 2:
            old = self.history.last()
            if old is not None:
                tids.add(old.tid)

        if not tids:
            self.logger.critical(_('No transaction ID, or package, given'))
            return 1, ['Failed history info']

        lastdbv = self.history.last()
        if lastdbv is not None:
            lasttid = lastdbv.tid
            lastdbv = lastdbv.end_rpmdbversion

        done = False
        for tid in self.history.old(tids):
            if lastdbv is not None and tid.tid == lasttid:
                #  If this is the last transaction, is good and it doesn't
                # match the current rpmdb ... then mark it as bad.
                rpmdbv  = self.rpmdb.simpleVersion(main_only=True)[0]
                if lastdbv != rpmdbv:
                    tid.altered_gt_rpmdb = True
            lastdbv = None

            if done:
                print "-" * 79
            done = True
            self._historyInfoCmd(tid, pats)

    def _historyInfoCmd(self, old, pats=[]):
        name = self._pwd_ui_username(old.loginuid)

        print _("Transaction ID :"), old.tid
        begtm = time.ctime(old.beg_timestamp)
        print _("Begin time     :"), begtm
        if old.beg_rpmdbversion is not None:
            if old.altered_lt_rpmdb:
                print _("Begin rpmdb    :"), old.beg_rpmdbversion, "**"
            else:
                print _("Begin rpmdb    :"), old.beg_rpmdbversion
        if old.end_timestamp is not None:
            endtm = time.ctime(old.end_timestamp)
            endtms = endtm.split()
            if begtm.startswith(endtms[0]): # Chop uninteresting prefix
                begtms = begtm.split()
                sofar = 0
                for i in range(len(endtms)):
                    if i > len(begtms):
                        break
                    if begtms[i] != endtms[i]:
                        break
                    sofar += len(begtms[i]) + 1
                endtm = (' ' * sofar) + endtm[sofar:]
            diff = _("(%s seconds)") % (old.end_timestamp - old.beg_timestamp)
            print _("End time       :"), endtm, diff
        if old.end_rpmdbversion is not None:
            if old.altered_gt_rpmdb:
                print _("End rpmdb      :"), old.end_rpmdbversion, "**"
            else:
                print _("End rpmdb      :"), old.end_rpmdbversion
        print _("User           :"), name
        if old.return_code is None:
            print _("Return-Code    :"), "**", _("Aborted"), "**"
        elif old.return_code:
            print _("Return-Code    :"), _("Failure:"), old.return_code
        else:
            print _("Return-Code    :"), _("Success")
        print _("Transaction performed with:")
        for hpkg in old.trans_with:
            prefix = " " * 4
            state  = _('Installed')
            ipkgs = self.rpmdb.searchNames([hpkg.name])
            ipkgs.sort()
            if not ipkgs:
                state  = _('Erased')
            elif hpkg.pkgtup in (ipkg.pkgtup for ipkg in ipkgs):
                pass
            elif ipkgs[-1] > hpkg:
                state  = _('Updated')
            elif ipkgs[0] < hpkg:
                state  = _('Downgraded')
            else: # multiple versions installed, both older and newer
                state  = _('Weird')
            print "%s%-12s %s" % (prefix, state, hpkg)
        print _("Packages Altered:")
        self.historyInfoCmdPkgsAltered(old, pats)
        if old.output:
            print _("Scriptlet output:")
            num = 0
            for line in old.output:
                num += 1
                print "%4d" % num, line
        if old.errors:
            print _("Errors:")
            num = 0
            for line in old.errors:
                num += 1
                print "%4d" % num, line

    def historyInfoCmdPkgsAltered(self, old, pats=[]):
        for hpkg in old.trans_data:
            prefix = " " * 4
            if not hpkg.done:
                prefix = " ** "

            highlight = 'normal'
            if pats:
                x,m,u = yum.packages.parsePackages([hpkg], pats)
                if x or m:
                    highlight = 'bold'
            (hibeg, hiend) = self._highlight(highlight)

            # To chop the name off we need nevra strings, str(pkg) gives envra
            # so we have to do it by hand ... *sigh*.
            if hpkg.epoch == '0':
                cn = str(hpkg)
            else:
                cn = "%s-%s:%s-%s.%s" % (hpkg.name, hpkg.epoch,
                                         hpkg.version, hpkg.release, hpkg.arch)

            if False: pass
            elif hpkg.state == 'Update':
                ln = len(hpkg.name) + 1
                cn = (" " * ln) + cn[ln:]
                print "%s%s%-12s%s %s" % (prefix, hibeg, hpkg.state, hiend, cn)
            elif hpkg.state == 'Downgraded':
                ln = len(hpkg.name) + 1
                cn = (" " * ln) + cn[ln:]
                print "%s%s%-12s%s %s" % (prefix, hibeg, hpkg.state, hiend, cn)
            elif hpkg.state == 'True-Install':
                print "%s%s%-12s%s %s" % (prefix, hibeg, "Install", hiend,  cn)
            else:
                print "%s%s%-12s%s %s" % (prefix, hibeg, hpkg.state, hiend, cn)

    def historySummaryCmd(self, extcmds):
        tids, printall = self._history_list_transactions(extcmds)
        if tids is None:
            return 1, ['Failed history info']

        fmt = "%-26s | %-19s | %-16s | %-8s"
        print fmt % ("Login user", "Time", "Action(s)", "Altered")
        print "-" * 79
        fmt = "%-26.26s | %-19.19s | %-16s | %8u"
        data = {'day' : {}, 'week' : {},
                'fortnight' : {}, 'quarter' : {}, 'half' : {}, 
                'year' : {}, 'all' : {}}
        for old in self.history.old(tids):
            name = self._pwd_ui_username(old.loginuid, 26)
            period = 'all'
            now = time.time()
            if False: pass
            elif old.beg_timestamp > (now - (24 * 60 * 60)):
                period = 'day'
            elif old.beg_timestamp > (now - (24 * 60 * 60 *  7)):
                period = 'week'
            elif old.beg_timestamp > (now - (24 * 60 * 60 * 14)):
                period = 'fortnight'
            elif old.beg_timestamp > (now - (24 * 60 * 60 *  7 * 13)):
                period = 'quarter'
            elif old.beg_timestamp > (now - (24 * 60 * 60 *  7 * 26)):
                period = 'half'
            elif old.beg_timestamp > (now - (24 * 60 * 60 * 365)):
                period = 'year'
            data[period].setdefault(name, []).append(old)
        _period2user = {'day'       : _("Last day"),
                        'week'      : _("Last week"),
                        'fortnight' : _("Last 2 weeks"), # US default :p
                        'quarter'   : _("Last 3 months"),
                        'half'      : _("Last 6 months"),
                        'year'      : _("Last year"),
                        'all'       : _("Over a year ago")}
        done = 0
        for period in ('day', 'week', 'fortnight', 'quarter', 'half', 'year',
                       'all'):
            if not data[period]:
                continue
            for name in sorted(data[period]):
                if not printall and done > 19:
                    break
                done += 1

                hpkgs = []
                for old in data[period][name]:
                    hpkgs.extend(old.trans_data)
                count, uiacts = self._history_uiactions(hpkgs)
                uperiod = _period2user[period]
                print fmt % (name, uperiod, uiacts, count)


class DepSolveProgressCallBack:
    """provides text output callback functions for Dependency Solver callback"""
    
    def __init__(self, ayum=None):
        """requires yum-cli log and errorlog functions as arguments"""
        self.verbose_logger = logging.getLogger("yum.verbose.cli")
        self.loops = 0
        self.ayum = ayum

    def pkgAdded(self, pkgtup, mode):
        modedict = { 'i': _('installed'),
                     'u': _('updated'),
                     'o': _('obsoleted'),
                     'e': _('erased')}
        (n, a, e, v, r) = pkgtup
        modeterm = modedict[mode]
        self.verbose_logger.log(logginglevels.INFO_2,
            _('---> Package %s.%s %s:%s-%s set to be %s'), n, a, e, v, r,
            modeterm)
        
    def start(self):
        self.loops += 1
        
    def tscheck(self):
        self.verbose_logger.log(logginglevels.INFO_2, _('--> Running transaction check'))
        
    def restartLoop(self):
        self.loops += 1
        self.verbose_logger.log(logginglevels.INFO_2,
            _('--> Restarting Dependency Resolution with new changes.'))
        self.verbose_logger.debug('---> Loop Number: %d', self.loops)
    
    def end(self):
        self.verbose_logger.log(logginglevels.INFO_2,
            _('--> Finished Dependency Resolution'))

    
    def procReq(self, name, formatted_req):
        self.verbose_logger.log(logginglevels.INFO_2,
            _('--> Processing Dependency: %s for package: %s'), formatted_req,
            name)

    def procReqPo(self, po, formatted_req):
        self.verbose_logger.log(logginglevels.INFO_2,
            _('--> Processing Dependency: %s for package: %s'), formatted_req,
            po)
    
    def unresolved(self, msg):
        self.verbose_logger.log(logginglevels.INFO_2, _('--> Unresolved Dependency: %s'),
            msg)

    
    def procConflict(self, name, confname):
        self.verbose_logger.log(logginglevels.INFO_2,
            _('--> Processing Conflict: %s conflicts %s'),
                                name, confname)

    def procConflictPo(self, po, confname):
        self.verbose_logger.log(logginglevels.INFO_2,
            _('--> Processing Conflict: %s conflicts %s'),
                                po, confname)

    def transactionPopulation(self):
        self.verbose_logger.log(logginglevels.INFO_2, _('--> Populating transaction set '
            'with selected packages. Please wait.'))
    
    def downloadHeader(self, name):
        self.verbose_logger.log(logginglevels.INFO_2, _('---> Downloading header for %s '
            'to pack into transaction set.'), name)
       

class CacheProgressCallback:

    '''
    The class handles text output callbacks during metadata cache updates.
    '''
    
    def __init__(self):
        self.logger = logging.getLogger("yum.cli")
        self.verbose_logger = logging.getLogger("yum.verbose.cli")
        self.file_logger = logging.getLogger("yum.filelogging.cli")

    def log(self, level, message):
        self.verbose_logger.log(level, message)

    def errorlog(self, level, message):
        self.logger.log(level, message)

    def filelog(self, level, message):
        self.file_logger.log(level, message)

    def progressbar(self, current, total, name=None):
        progressbar(current, total, name)

def _pkgname_ui(ayum, pkgname, ts_states=None):
    """ Get more information on a simple pkgname, if we can. We need to search
        packages that we are dealing with atm. and installed packages (if the
        transaction isn't complete). """
    if ayum is None:
        return pkgname

    if ts_states is None:
        #  Note 'd' is a placeholder for downgrade, and
        # 'r' is a placeholder for reinstall. Neither exist atm.
        ts_states = ('d', 'e', 'i', 'r', 'u')

    matches = []
    def _cond_add(po):
        if matches and matches[0].arch == po.arch and matches[0].verEQ(po):
            return
        matches.append(po)

    for txmbr in ayum.tsInfo.matchNaevr(name=pkgname):
        if txmbr.ts_state not in ts_states:
            continue
        _cond_add(txmbr.po)

    if not matches:
        return pkgname
    fmatch = matches.pop(0)
    if not matches:
        return str(fmatch)

    show_ver  = True
    show_arch = True
    for match in matches:
        if not fmatch.verEQ(match):
            show_ver  = False
        if fmatch.arch != match.arch:
            show_arch = False

    if show_ver: # Multilib. *sigh*
        if fmatch.epoch == '0':
            return '%s-%s-%s' % (fmatch.name, fmatch.version, fmatch.release)
        else:
            return '%s:%s-%s-%s' % (fmatch.epoch, fmatch.name,
                                    fmatch.version, fmatch.release)

    if show_arch:
        return '%s.%s' % (fmatch.name, fmatch.arch)

    return pkgname

class YumCliRPMCallBack(RPMBaseCallback):

    """
    Yum specific callback class for RPM operations.
    """

    width = property(lambda x: _term_width())

    def __init__(self, ayum=None):
        RPMBaseCallback.__init__(self)
        self.lastmsg = to_unicode("")
        self.lastpackage = None # name of last package we looked at
        self.output = logging.getLogger("yum.verbose.cli").isEnabledFor(logginglevels.INFO_2)
        
        # for a progress bar
        self.mark = "#"
        self.marks = 22
        self.ayum = ayum

    #  Installing things have pkg objects passed to the events, so only need to
    # lookup for erased/obsoleted.
    def pkgname_ui(self, pkgname, ts_states=('e', None)):
        """ Get more information on a simple pkgname, if we can. """
        return _pkgname_ui(self.ayum, pkgname, ts_states)

    def event(self, package, action, te_current, te_total, ts_current, ts_total):
        # this is where a progress bar would be called
        process = self.action[action]
        
        if type(package) not in types.StringTypes:
            pkgname = str(package)
        else:
            pkgname = self.pkgname_ui(package)
            
        self.lastpackage = package
        if te_total == 0:
            percent = 0
        else:
            percent = (te_current*100L)/te_total
        
        if self.output and (sys.stdout.isatty() or te_current == te_total):
            (fmt, wid1, wid2) = self._makefmt(percent, ts_current, ts_total,
                                              pkgname=pkgname)
            msg = fmt % (utf8_width_fill(process, wid1, wid1),
                         utf8_width_fill(pkgname, wid2, wid2))
            if msg != self.lastmsg:
                sys.stdout.write(to_unicode(msg))
                sys.stdout.flush()
                self.lastmsg = msg
            if te_current == te_total:
                print " "

    def scriptout(self, package, msgs):
        if msgs:
            sys.stdout.write(to_unicode(msgs))
            sys.stdout.flush()

    def _makefmt(self, percent, ts_current, ts_total, progress = True,
                 pkgname=None):
        l = len(str(ts_total))
        size = "%s.%s" % (l, l)
        fmt_done = "%" + size + "s/%" + size + "s"
        done = fmt_done % (ts_current, ts_total)

        #  This should probably use TerminLine, but we don't want to dep. on
        # that. So we kind do an ok job by hand ... at least it's dynamic now.
        if pkgname is None:
            pnl = 22
        else:
            pnl = utf8_width(pkgname)

        overhead  = (2 * l) + 2 # Length of done, above
        overhead += 19          # Length of begining
        overhead +=  1          # Space between pn and done
        overhead +=  2          # Ends for progress
        overhead +=  1          # Space for end
        width = self.width
        if width < overhead:
            width = overhead    # Give up
        width -= overhead
        if pnl > width / 2:
            pnl = width / 2

        marks = self.width - (overhead + pnl)
        width = "%s.%s" % (marks, marks)
        fmt_bar = "[%-" + width + "s]"
        # pnl = str(28 + marks + 1)
        full_pnl = pnl + marks + 1

        if progress and percent == 100: # Don't chop pkg name on 100%
            fmt = "\r  %s: %s   " + done
            wid2 = full_pnl
        elif progress:
            bar = fmt_bar % (self.mark * int(marks * (percent / 100.0)), )
            fmt = "\r  %s: %s " + bar + " " + done
            wid2 = pnl
        elif percent == 100:
            fmt = "  %s: %s   " + done
            wid2 = full_pnl
        else:
            bar = fmt_bar % (self.mark * marks, )
            fmt = "  %s: %s " + bar + " " + done
            wid2 = pnl
        return fmt, 15, wid2


def progressbar(current, total, name=None):
    """simple progress bar 50 # marks"""
    
    mark = '#'
    if not sys.stdout.isatty():
        return
        
    if current == 0:
        percent = 0 
    else:
        if total != 0:
            percent = float(current) / total
        else:
            percent = 0

    width = _term_width()

    if name is None and current == total:
        name = '-'

    end = ' %d/%d' % (current, total)
    width -= len(end) + 1
    if width < 0:
        width = 0
    if name is None:
        width -= 2
        if width < 0:
            width = 0
        hashbar = mark * int(width * percent)
        output = '\r[%-*s]%s' % (width, hashbar, end)
    elif current == total: # Don't chop name on 100%
        output = '\r%s%s' % (utf8_width_fill(name, width, width), end)
    else:
        width -= 4
        if width < 0:
            width = 0
        nwid = width / 2
        if nwid > utf8_width(name):
            nwid = utf8_width(name)
        width -= nwid
        hashbar = mark * int(width * percent)
        output = '\r%s: [%-*s]%s' % (utf8_width_fill(name, nwid, nwid), width,
                                     hashbar, end)
     
    if current <= total:
        sys.stdout.write(output)

    if current == total:
        sys.stdout.write('\n')

    sys.stdout.flush()
        

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "progress":
        print ""
        print " Doing progress, small name"
        print ""
        for i in xrange(0, 101):
            progressbar(i, 100, "abcd")
            time.sleep(0.1)
        print ""
        print " Doing progress, big name"
        print ""
        for i in xrange(0, 101):
            progressbar(i, 100, "_%s_" % ("123456789 " * 5))
            time.sleep(0.1)
        print ""
        print " Doing progress, no name"
        print ""
        for i in xrange(0, 101):
            progressbar(i, 100)
            time.sleep(0.1)

    if len(sys.argv) > 1 and sys.argv[1] in ("progress", "rpm-progress"):
        cb = YumCliRPMCallBack()
        cb.output = True
        cb.action["foo"] = "abcd"
        cb.action["bar"] = "_12345678_.end"
        print ""
        print " Doing CB, small proc / small pkg"
        print ""
        for i in xrange(0, 101):
            cb.event("spkg", "foo", i, 100, i, 100)
            time.sleep(0.1)        
        print ""
        print " Doing CB, big proc / big pkg"
        print ""
        for i in xrange(0, 101):
            cb.event("lpkg" + "-=" * 15 + ".end", "bar", i, 100, i, 100)
            time.sleep(0.1)

    if len(sys.argv) > 1 and sys.argv[1] in ("progress", "i18n-progress",
                                             "rpm-progress",
                                             'i18n-rpm-progress'):
        yum.misc.setup_locale()
    if len(sys.argv) > 1 and sys.argv[1] in ("progress", "i18n-progress"):
        print ""
        print " Doing progress, i18n: small name"
        print ""
        for i in xrange(0, 101):
            progressbar(i, 100, to_unicode('\xe6\xad\xa3\xe5\x9c\xa8\xe5\xae\x89\xe8\xa3\x85'))
            time.sleep(0.1)
        print ""

        print ""
        print " Doing progress, i18n: big name"
        print ""
        for i in xrange(0, 101):
            progressbar(i, 100, to_unicode('\xe6\xad\xa3\xe5\x9c\xa8\xe5\xae\x89\xe8\xa3\x85' * 5 + ".end"))
            time.sleep(0.1)
        print ""


    if len(sys.argv) > 1 and sys.argv[1] in ("progress", "i18n-progress",
                                             "rpm-progress",
                                             'i18n-rpm-progress'):
        cb = YumCliRPMCallBack()
        cb.output = True
        cb.action["foo"] = to_unicode('\xe6\xad\xa3\xe5\x9c\xa8\xe5\xae\x89\xe8\xa3\x85')
        cb.action["bar"] = cb.action["foo"] * 5 + ".end"
        print ""
        print " Doing CB, i18n: small proc / small pkg"
        print ""
        for i in xrange(0, 101):
            cb.event("spkg", "foo", i, 100, i, 100)
            time.sleep(0.1)        
        print ""
        print " Doing CB, i18n: big proc / big pkg"
        print ""
        for i in xrange(0, 101):
            cb.event("lpkg" + "-=" * 15 + ".end", "bar", i, 100, i, 100)
            time.sleep(0.1)
        print ""