summaryrefslogtreecommitdiffstats
path: root/layman/action.py
blob: 02ba1ce041000e84382948d445c810b0b97712d3 (plain)
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#################################################################################
# LAYMAN ACTIONS
#################################################################################
# File:       action.py
#
#             Handles layman actions.
#
# Copyright:
#             (c) 2005 - 2008 Gunnar Wrobel
#             Distributed under the terms of the GNU General Public License v2
#
# Author(s):
#             Gunnar Wrobel <wrobel@gentoo.org>
#
''' Provides the different actions that can be performed by layman.'''

__version__ = "$Id: action.py 312 2007-04-09 19:45:49Z wrobel $"

#===============================================================================
#
# Dependencies
#
#-------------------------------------------------------------------------------

import os, sys

from   layman.db                import DB, RemoteDB

from   layman.debug             import OUT

#===============================================================================
#
# Class Fetch
#
#-------------------------------------------------------------------------------

class Fetch:
    ''' Fetches the overlay listing.

    >>> import os
    >>> here = os.path.dirname(os.path.realpath(__file__))
    >>> cache = os.tmpnam()
    >>> config = {'overlays' :
    ...           'file://' + here + '/tests/testfiles/global-overlays.xml',
    ...           'cache' : cache,
    ...           'nocheck'    : True,
    ...           'proxy' : None,
    ...           'quietness':3,
    ...           'svn_command':'/usr/bin/svn',
    ...           'rsync_command':'/usr/bin/rsync'}
    >>> a = Fetch(config)
    >>> a.run()
    0
    >>> b = open(a.db.path(config['overlays']))
    >>> b.readlines()[24]
    '      A collection of ebuilds from Gunnar Wrobel [wrobel@gentoo.org].\\n'

    >>> b.close()
    >>> os.unlink(a.db.path(config['overlays']))

    >>> a.db.overlays.keys()
    [u'wrobel', u'wrobel-stable']
    '''

    def __init__(self, config):
        self.db = RemoteDB(config)

    def run(self):
        '''Fetch the overlay listing.'''
        try:
            self.db.cache()
        except Exception, error:
            OUT.die('Failed to fetch overlay list!\nError was: '
                    + str(error))

        return 0

#===============================================================================
#
# Class Sync
#
#-------------------------------------------------------------------------------

class Sync:
    ''' Syncs the selected overlays.'''

    def __init__(self, config):

        self.db = DB(config)

        self.rdb = RemoteDB(config)

        self.quiet = int(config['quietness']) < 3

        self.selection = config['sync']

	if config['sync_all'] or 'ALL' in self.selection:
	    self.selection = self.db.overlays.keys()

        enc = sys.getfilesystemencoding()
        if enc:
            self.selection = [i.decode(enc) for i in self.selection]

    def run(self):
        '''Synchronize the overlays.'''

        OUT.debug('Updating selected overlays', 6)

        warnings = []
        success  = []
        for i in self.selection:
            try:
                ordb = self.rdb.select(i)
            except:
                warnings.append(\
                    'Overlay "%s" could not be found in the remote lists.\n'
                    'Please check if it has been renamed and re-add if necessary.' % i)
            else:
                odb = self.db.select(i)
                current_src = odb.sources[0].src
                available_srcs = set(e.src for e in ordb.sources)
                if ordb and odb and not current_src in available_srcs:
                    if len(available_srcs) == 1:
                        plural = ''
                        candidates = '  %s' % tuple(available_srcs)[0]
                    else:
                        plural = 's'
                        candidates = '\n'.join(('  %d. %s' % (i + 1, v)) for i, v in enumerate(available_srcs))

                    warnings.append(
                        'The source of the overlay "%(repo_name)s" seems to have changed.\n'
                        'You currently sync from\n'
                        '\n'
                        '  %(current_src)s\n'
                        '\n'
                        'while the remote lists report\n'
                        '\n'
                        '%(candidates)s\n'
                        '\n'
                        'as correct location%(plural)s.\n'
                        'Please consider removing and re-adding the overlay.' % {
                            'repo_name':i,
                            'current_src':current_src,
                            'candidates':candidates,
                            'plural':plural,
                            })

            try:
                self.db.sync(i, self.quiet)
                success.append('Successfully synchronized overlay "' + i + '".')
            except Exception, error:
                warnings.append(
                    'Failed to sync overlay "' + i + '".\nError was: '
                    + str(error))

        if success:
            OUT.info('\nSuccess:\n------\n', 3)
            for i in success:
                OUT.info(i, 3)
                
        if warnings:
            OUT.warn('\nErrors:\n------\n', 2)
            for i in warnings:
                OUT.warn(i + '\n', 2)
            return 1

        return 0

#===============================================================================
#
# Class Add
#
#-------------------------------------------------------------------------------

class Add:
    ''' Adds the selected overlays.'''

    def __init__(self, config):

        self.config = config

        self.db = DB(config)

        self.rdb = RemoteDB(config)

        self.quiet = int(config['quietness']) < 3

        self.selection = config['add']

        enc = sys.getfilesystemencoding()
        if enc:
            self.selection = [i.decode(enc) for i in self.selection]

        if 'ALL' in self.selection:
            self.selection = self.rdb.overlays.keys()

    def run(self):
        '''Add the overlay.'''

        OUT.debug('Adding selected overlays', 6)

        result = 0

        for i in self.selection:
            overlay = self.rdb.select(i)

            OUT.debug('Selected overlay', 7)

            if overlay:
                try:
                    self.db.add(overlay, self.quiet)
                    OUT.info('Successfully added overlay "' + i + '".', 2)
                except Exception, error:
                    OUT.warn('Failed to add overlay "' + i + '".\nError was: '
                             + str(error), 2)
                    result = 1
            else:
                OUT.warn('Overlay "' + i + '" does not exist!', 2)
                result = 1

        return result

#===============================================================================
#
# Class Delete
#
#-------------------------------------------------------------------------------

class Delete:
    ''' Deletes the selected overlays.'''

    def __init__(self, config):

        self.db = DB(config)

        self.selection = config['delete']

        enc = sys.getfilesystemencoding()
        if enc:
            self.selection = [i.decode(enc) for i in self.selection]

        if 'ALL' in self.selection:
            self.selection = self.db.overlays.keys()

    def run(self):
        '''Delete the overlay.'''

        OUT.debug('Deleting selected overlays', 6)

        result = 0

        for i in self.selection:
            overlay = self.db.select(i)

            OUT.debug('Selected overlay', 7)

            if overlay:
                try:
                    self.db.delete(overlay)
                    OUT.info('Successfully deleted overlay "' + i + '".', 2)
                except Exception, error:
                    OUT.warn('Failed to delete overlay "' + i + '".\nError was: '
                             + str(error), 2)
                    result = 1
            else:
                OUT.warn('Overlay "' + i + '" does not exist!', 2)
                result = 1

        return result

#===============================================================================
#
# Class Info
#
#-------------------------------------------------------------------------------

class Info:
    ''' Print information about the specified overlays.

    >>> import os
    >>> here = os.path.dirname(os.path.realpath(__file__))
    >>> cache = os.tmpnam()
    >>> config = {'overlays' :
    ...           'file://' + here + '/tests/testfiles/global-overlays.xml',
    ...           'cache'  : cache,
    ...           'proxy'  : None,
    ...           'info'   : ['wrobel'],
    ...           'nocheck'    : False,
    ...           'verbose': False,
    ...           'quietness':3,
    ...           'svn_command':'/usr/bin/svn',
    ...           'rsync_command':'/usr/bin/rsync'}
    >>> a = Info(config)
    >>> a.rdb.cache()
    >>> OUT.color_off()
    >>> a.run()
    * wrobel
    * ~~~~~~
    * Source  : https://overlays.gentoo.org/svn/dev/wrobel
    * Contact : nobody@gentoo.org
    * Type    : Subversion; Priority: 10
    * Quality : experimental
    * 
    * Description:
    *   Test
    * 
    0
    '''

    def __init__(self, config):

        OUT.debug('Creating RemoteDB handler', 6)

        self.rdb    = RemoteDB(config)
        self.config = config

        self.selection = config['info']

        enc = sys.getfilesystemencoding()
        if enc:
            self.selection = [i.decode(enc) for i in self.selection]

        if 'ALL' in self.selection:
            self.selection = self.rdb.overlays.keys()

    def run(self):
        ''' Print information about the selected overlays.'''

        result = 0

        for i in self.selection:
            overlay = self.rdb.select(i)

            if overlay:
                # Is the overlay supported?
                OUT.info(overlay.__str__(), 1)
                if not overlay.is_official():
                    OUT.warn('*** This is no official gentoo overlay ***\n', 1)
                if not overlay.is_supported():
                    OUT.error('*** You are lacking the necessary tools to install t'
                              'his overlay ***\n')
            else:
                OUT.warn('Overlay "' + i + '" does not exist!', 2)
                result = 1

        return result

#===============================================================================
#
# Class List
#
#-------------------------------------------------------------------------------

class List:
    ''' Lists the available overlays.

    >>> import os
    >>> here = os.path.dirname(os.path.realpath(__file__))
    >>> cache = os.tmpnam()
    >>> config = {'overlays' :
    ...           'file://' + here + '/tests/testfiles/global-overlays.xml',
    ...           'cache'  : cache,
    ...           'proxy'  : None,
    ...           'nocheck'    : False,
    ...           'verbose': False,
    ...           'quietness':3,
    ...           'width':80,
    ...           'svn_command':'/usr/bin/svn',
    ...           'rsync_command':'/usr/bin/rsync'}
    >>> a = List(config)
    >>> a.rdb.cache()
    >>> OUT.color_off()
    >>> a.run()
    * wrobel                    [Subversion] (https://o.g.o/svn/dev/wrobel         )
    0
    >>> a.config['verbose'] = True
    >>> a.run()
    * wrobel
    * ~~~~~~
    * Source  : https://overlays.gentoo.org/svn/dev/wrobel
    * Contact : nobody@gentoo.org
    * Type    : Subversion; Priority: 10
    * Quality : experimental
    * 
    * Description:
    *   Test
    * 
    * *** This is no official gentoo overlay ***
    * 
    * wrobel-stable
    * ~~~~~~~~~~~~~
    * Source  : rsync://gunnarwrobel.de/wrobel-stable
    * Contact : nobody@gentoo.org
    * Type    : Rsync; Priority: 50
    * Quality : experimental
    * 
    * Description:
    *   A collection of ebuilds from Gunnar Wrobel [wrobel@gentoo.org].
    * 
    0
    '''

    def __init__(self, config):

        OUT.debug('Creating RemoteDB handler', 6)

        self.rdb    = RemoteDB(config)
        self.config = config

    def run(self):
        ''' List the available overlays.'''

        for i in self.rdb.list(self.config['verbose'], self.config['width']):
            # Is the overlay supported?
            if i[1]:
                # Is this an official overlay?
                if i[2]:
                    OUT.info(i[0], 1)
                # Unofficial overlays will only be listed if we are not
                # checking or listing verbose
                elif self.config['nocheck'] or self.config['verbose']:
                    # Give a reason why this is marked yellow if it is a verbose
                    # listing
                    if self.config['verbose']:
                        OUT.warn('*** This is no official gentoo overlay ***\n', 1)
                    OUT.warn(i[0], 1)
            # Unsupported overlays will only be listed if we are not checking
            # or listing verbose
            elif self.config['nocheck'] or self.config['verbose']:
                # Give a reason why this is marked red if it is a verbose
                # listing
                if self.config['verbose']:
                    OUT.error('*** You are lacking the necessary tools to insta'
                              'll this overlay ***\n')
                OUT.error(i[0])

        return 0

#===============================================================================
#
# Class ListLocal
#
#-------------------------------------------------------------------------------

class ListLocal:
    ''' Lists the local overlays.'''

    def __init__(self, config):
        self.db = DB(config)
        self.config = config

    def run(self):
        '''List the overlays.'''

        for i in self.db.list(self.config['verbose']):

            OUT.debug('Printing local overlay.', 8)

            # Is the overlay supported?
            if i[1]:
                # Is this an official overlay?
                if i[2]:
                    OUT.info(i[0], 1)
                # Unofficial overlays will only be listed if we are not
                # checking or listing verbose
                else:
                    # Give a reason why this is marked yellow if it is a verbose
                    # listing
                    if self.config['verbose']:
                        OUT.warn('*** This is no official gentoo overlay ***\n', 1)
                    OUT.warn(i[0], 1)
            # Unsupported overlays will only be listed if we are not checking
            # or listing verbose
            else:
                # Give a reason why this is marked red if it is a verbose
                # listing
                if self.config['verbose']:
                    OUT.error('*** You are lacking the necessary tools to insta'
                              'll this overlay ***\n')
                OUT.error(i[0])

        return 0

#===============================================================================
#
# Class Actions
#
#-------------------------------------------------------------------------------

class Actions:
    '''Dispatches to the actions the user selected. '''

    # Given in order of precedence
    actions = [('fetch',      Fetch),
               ('add',        Add),
               ('sync',       Sync),
               ('info',       Info),
               ('sync_all',   Sync),
               ('delete',     Delete),
               ('list',       List),
               ('list_local', ListLocal),]

    def __init__(self, config):

        # Make fetching the overlay list a default action
        if not 'nofetch' in config.keys():
            # Actions that implicitely call the fetch operation before
            fetch_actions = ['sync', 'sync_all', 'list']
            for i in fetch_actions:
                if i in config.keys():
                    # Implicitely call fetch, break loop
                    Fetch(config).run()
                    break

        result = 0

        # Set the umask
        umask = config['umask']
        try:
            new_umask = int(umask, 8)
            old_umask = os.umask(new_umask)
        except Exception, error:
            OUT.die('Failed setting to umask "' + umask + '"!\nError was: ' 
                    + str(error))

        for i in self.actions:

            OUT.debug('Checking for action', 7)

            if i[0] in config.keys():
                result += i[1](config).run()

        # Reset umask
        os.umask(old_umask)

        if not result:
            sys.exit(0)
        else:
            sys.exit(1)
            
#===============================================================================
#
# Testing
#
#-------------------------------------------------------------------------------

if __name__ == '__main__':
    import doctest, sys

    # Ignore warnings here. We are just testing
    from warnings     import filterwarnings, resetwarnings
    filterwarnings('ignore')

    doctest.testmod(sys.modules[__name__])

    resetwarnings()