File: output.py

package info (click to toggle)
yum 2.4.0-3.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,252 kB
  • ctags: 1,149
  • sloc: python: 11,641; makefile: 155; sh: 55
file content (484 lines) | stat: -rw-r--r-- 17,175 bytes parent folder | download
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
#!/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 os
import os.path
import sys
import time
from i18n import _

from urlgrabber.progress import TextMeter

try:
    import readline
except:
    pass

import yum.Errors

class YumOutput:

    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.errorlog(1, '%s: %s' % (errobj.url, str(errobj.exception)))
        self.errorlog(1, 'Trying other mirror.')
        raise errobj.exception
    
        
    def simpleProgressBar(self, current, total, name=None):
        progressbar(current, total, name)
    
    def simpleList(self, pkg):
        ver = pkg.printVer()
        na = '%s.%s' % (pkg.name, pkg.arch)
        repo = pkg.returnSimple('repoid')
        
        print "%-40.40s %-22.22s %-16.16s" % (na, ver, repo)
    
        
    def infoOutput(self, pkg):
        print _("Name   : %s") % pkg.name
        print _("Arch   : %s") % pkg.arch
        print _("Version: %s") % pkg.version
        print _("Release: %s") % pkg.release
        print _("Size   : %s") % self.format_number(float(pkg.size()))
        print _("Repo   : %s") % pkg.returnSimple('repoid')
        print _("Summary: %s") % pkg.returnSimple('summary')
        print _("Description:\n %s") % pkg.returnSimple('description')
        print ""
    
    def updatesObsoletesList(self, uotup, changetype):
        """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
        c_compact = changePkg.compactPrint()
        i_compact = '%s.%s' % (instPkg.name, instPkg.arch)
        c_repo = changePkg.repoid
        # FIXME - other ideas for how to print this out?
        print '%-35.35s [%.12s] %.10s %-20.20s' % (c_compact, c_repo, changetype, i_compact)

    def listPkgs(self, lst, description, outputType):
        """outputs based on whatever outputType is. Current options:
           'list' - simple pkg list
           'info' - similar to rpm -qi output"""
        
        if outputType in ['list', 'info']:
            thingslisted = 0
            if len(lst) > 0:
                thingslisted = 1
                print '%s' % description
                lst.sort(self.sortPkgObj)
                for pkg in lst:
                    if outputType == 'list':
                        self.simpleList(pkg)
                    elif outputType == 'info':
                        self.infoOutput(pkg)
                    else:
                        pass
    
            if thingslisted == 0:
                return 1, ['No Packages to list']
        
    
        
    def userconfirm(self):
        """gets a yes or no from the user, defaults to No"""

        while True:            
            choice = raw_input('Is this ok [y/N]: ')
            choice = choice.lower()
            if len(choice) == 0 or choice[0] in ['y', 'n']:
                break

        if len(choice) == 0 or choice[0] != 'y':
            return False
        else:            
            return True
                
    
    def displayPkgsInGroups(self, group):
        print '\nGroup: %s' % group
        groupid = self.groupInfo.matchGroup(group)
        if len(self.groupInfo.sub_groups[groupid]) > 0:
            print ' Required Groups:'
            for id in self.groupInfo.sub_groups[groupid]:
                grp = self.groupInfo.group_by_id[id]
                print '   %s' % grp.name
        if len(self.groupInfo.default_metapkgs[groupid]) > 0:
            print ' Default Metapkgs:'
            for id in self.groupInfo.default_metapkgs[groupid]:
                grp = self.groupInfo.group_by_id[id]
                print '   %s' % grp.name
        if len(self.groupInfo.optional_metapkgs[groupid]) > 0:
            print ' Optional Metapkgs:'
            for id in self.groupInfo.optional_metapkgs[groupid]:
                grp = self.groupInfo.group_by_id[id]
                print '   %s' % grp.name
        if len(self.groupInfo.mandatory_pkgs[groupid]) > 0:
            print ' Mandatory Packages:'
            for item in self.groupInfo.mandatory_pkgs[groupid]:
                print '   %s' % item
        if len(self.groupInfo.default_pkgs[groupid]) > 0:
            print ' Default Packages:'
            for item in self.groupInfo.default_pkgs[groupid]:
                print '   %s' % item
        if len(self.groupInfo.optional_pkgs[groupid]) > 0:
            print ' Optional Packages'
            for item in self.groupInfo.optional_pkgs[groupid]:
                print '   %s' % item


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

            for req in results[pkg].keys():
                reqlist = results[pkg][req] 
                print "  dependency: %s" % pkg.prcoPrintable(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
    
        # we want numbers between 
        while number > thresh:
            depth  = depth + 1
            number = number / step
    
        # just in case someone needs more than 1000 yottabytes!
        diff = depth - len(symbols) + 1
        if diff > 0:
            depth = depth - diff
            number = number * thresh**depth
    
        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 % (number, space, symbols[depth]))

    def matchcallback(self, po, values):
        self.log(2, '\n\n')
        self.simpleList(po)
        self.log(2, 'Matched from:')
        for item in values:
            self.log(2, '%s' % item)

    def reportDownloadSize(self, packages):
        """Report the total download size for a set of packages"""
        totsize = 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
            except:
                 error = True
                 self.errorlog(1, 'There was an error calculating total download size')
                 break

        if (not error):
            self.log(1, "Total download size: %s" % (self.format_number(totsize)))
            
    def listTransaction(self):
        """returns a string rep of the  transaction in an easy-to-read way."""
        
        self.tsInfo.makelists()
        if len(self.tsInfo) > 0:
            out = """
=============================================================================
 %-22s  %-9s  %-15s  %-16s  %-5s
=============================================================================
""" % ('Package', 'Arch', 'Version', 'Repository', 'Size')
        else:
            out = ""

        for (action, pkglist) in [('Installing', self.tsInfo.installed),
                            ('Updating', self.tsInfo.updated),
                            ('Removing', self.tsInfo.removed),
                            ('Installing for dependencies', self.tsInfo.depinstalled),
                            ('Updating for dependencies', self.tsInfo.depupdated),
                            ('Removing for dependencies', self.tsInfo.depremoved)]:
            if pkglist:
                totalmsg = "%s:\n" % action
            for txmbr in pkglist:
                (n,a,e,v,r) = txmbr.pkgtup
                evr = txmbr.po.printVer()
                repoid = txmbr.repoid
                pkgsize = float(txmbr.po.size())
                size = self.format_number(pkgsize)
                msg = " %-22s  %-9s  %-15s  %-16s  %5s\n" % (n, a,
                              evr, repoid, size)
                for (obspo, relationship) in txmbr.relatedto:
                    if relationship == 'obsoletes':
                        appended = '     replacing  %s.%s %s\n\n' % (obspo.name,
                            obspo.arch, obspo.printVer())
                        msg = msg+appended
                totalmsg = totalmsg + msg
        
            if pkglist:
                out = out + totalmsg

        summary = """
Transaction Summary
=============================================================================
Install  %5.5s Package(s)         
Update   %5.5s Package(s)         
Remove   %5.5s Package(s)         
""" % (len(self.tsInfo.installed + self.tsInfo.depinstalled),
       len(self.tsInfo.updated + self.tsInfo.depupdated),
       len(self.tsInfo.removed + self.tsInfo.depremoved))
        out = out + summary
        
        return out
        
    def postTransactionOutput(self):
        out = ''
        
        self.tsInfo.makelists()

        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),
                                  ('Replaced', self.tsInfo.obsoleted)]:
            
            if len(pkglist) > 0:
                out += '\n%s:' % action
                for txmbr in pkglist:
                    (n,a,e,v,r) = txmbr.pkgtup
                    msg = " %s.%s %s:%s-%s" % (n,a,e,v,r)
                    out += msg
        
        return out

    def setupProgessCallbacks(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(TextMeter(fo=sys.stdout))
            self.repos.callback = CacheProgressCallback(self.log, self.errorlog,
                                                        self.filelog)
        # setup our failure report for failover
        freport = (self.failureReport,(),{})
        self.repos.setFailureCallback(freport)
        
        # setup our depsolve progress callback
        dscb = DepSolveProgressCallBack(self.log, self.errorlog)
        self.dsCallback = dscb
            
    
    def pickleRecipe(self):
        """ don't ask """
        
        recipe = """
        
                        7 Day Sweet Pickle Recipe

Recipe By     : Simply Good Cooking Pennsylvanis Dutch Style
Serving Size  : 1    Preparation Time :0:00
Categories    : Canned                           Pickles

  Amount  Measure       Ingredient -- Preparation Method
--------  ------------  --------------------------------
   7      pounds        cucumber
                        water to cover
   1      quart         vinegar
   8      cups          sugar
   2      tablespoons   salt
   2      tablespoons   mixed pickle spices

Wash cucumbers & cover with boiling water.  Let stand 24 hours and repeat
process daily using fresh hot water until the 5th day.  On the 5th morning,
cut cucumbers into 1/4 inch rings.  Prepare vinegar brine: bring vinegar,
sugar, salt & spices to a boil.  Pour over cucmbers.  let stand 24 hours.
The next morning, drain off brine; reheat, add cucmbers & bring to a boil.
Pack in jars & seal while hot.

                   - - - - - - - - - - - - - - - - - -

NOTES : This should be processed in a boiling water bath to avoid risk of
contamination.        


"""
        return recipe
    

class DepSolveProgressCallBack:
    """provides text output callback functions for Dependency Solver callback"""
    
    def __init__(self, log, errorlog):
        """requires yum-cli log and errorlog functions as arguments"""
        self.log = log
        self.errorlog = errorlog
        self.loops = 0
    
    def pkgAdded(self, pkgtup, mode):
        modedict = { 'i': 'installed',
                     'u': 'updated',
                     'o': 'obsoleted',
                     'e': 'erased'}
        (n, a, e, v, r) = pkgtup
        modeterm = modedict[mode]
        self.log(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.log(2, '--> Running transaction check')
        
    def restartLoop(self):
        self.loops += 1
        self.log(2, '--> Restarting Dependency Resolution with new changes.')
        self.log(3, '---> Loop Number: %d' % self.loops)
    
    def end(self):
        self.log(2, '--> Finished Dependency Resolution')

    
    def procReq(self, name, formatted_req):
        self.log(2, '--> Processing Dependency: %s for package: %s' % (formatted_req, name))
        
    
    def unresolved(self, msg):
        self.log(2, '--> Unresolved Dependency: %s' % msg)

    
    def procConflict(self, name, confname):
        self.log(2, '--> Processing Conflict: %s conflicts %s' % (name, confname))

    def transactionPopulation(self):
        self.log(2, '--> Populating transaction set with selected packages. Please wait.')
    
    def downloadHeader(self, name):
        self.log(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, log, errorlog, filelog=None):
        self.log = log
        self.errorlog = errorlog
        self.filelog = filelog

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

    def errorlog(self, level, message):
        if self.errorlog:
            self.errorlog(level, message)

    def filelog(self, level, message):
        if self.filelog:
            self.filelog(level, message)

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


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 = current*100/total
        else:
            percent = 0

    numblocks = int(percent/2)
    hashbar = mark * numblocks
    if name is None:
        output = '\r%-50s %d/%d' % (hashbar, current, total)
    else:
        output = '\r%-10.10s: %-50s %d/%d' % (name, hashbar, current, total)
     
    if current <= total:
        sys.stdout.write(output)

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

    sys.stdout.flush()