summaryrefslogtreecommitdiffstats
path: root/layman/api.py
blob: e17d70ea60cc0fa6c3e73c30888f4657d36a9bed (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
#!python
# -*- coding: utf-8 -*-
#######################################################################
# LAYMAN - A UTILITY TO SELECT AND UPDATE GENTOO OVERLAYS
#######################################################################
# Distributed under the terms of the GNU General Public License v2
#
# Copyright:
#             (c) 2010 Brian Dolbec
#             Distributed under the terms of the GNU General Public License v2
#
# Author(s):
#              Brian Dolbec <dol-sen@sourceforge.net>
#

from sys import stderr, stdin, stdout
import os, types

from layman.config import BareConfig
#from layman.action import Sync

from layman.dbbase import UnknownOverlayException
from layman.db import DB, RemoteDB
#from layman.utils import path, delete_empty_directory
from layman.debug import Message, OUT

# give them some values for now, these are from the packagekit backend
# TODO  establish some proper errors for the api.
ERROR_REPO_NOT_FOUND = -1
ERROR_INTERNAL_ERROR = -2
UNKNOWN_REPO_ID = "Repo ID '%s' " + \
        "is not listed in the current available overlays list"
 
# In order to redirect output you need to get a Message class instance with the
# stderr, stdout, stddebug directed to where you want.
# eg:  output = Message('layman', err=mystderr, dbg=mydebug, out=myoutput)
# there are many more options available, refer to debug.py Message class


class LaymanAPI(object):
    """class to hold and run a layman instance for use by API consumer apps, guis, etc.
    """
    ## hell, even the current cli should probably be converted to use this one.
    ## It is a near duplicate of the actions classes.

    def __init__(self, config=None, report_errors=False, output=None):
        """@param configfile, optional config file to use instead of the default
        """
        
        self.output = output if output  else OUT
       
        self.config = config if config else BareConfig(output=output)
        
        self.report_errors = report_errors
        
        # get installed and available dbs
        self._installed_db = None
        self._installed_ids = None
        self._available_db = None
        self._available_ids = None
        self._error_messages = []
        self.sync_results = []
        # call reload() for now to initialize the 2 db's
        self.reload()
        # change it to delayed loading (similar to delayed imports)
        # to simplify some of the code and make it automagic.


    def is_repo(self, id):
        """validates that the id given is a known repo id
        
        @param id: repo id
        @type id: str
        @rtype boolean
        """
        return id in self._available_ids


    def is_installed(self, id):
        """checks the repo id is a known installed repo id
        
        @param id: repo id
        @type id: str
        @rtype boolean
        """
        return id in self._installed_ids


    @staticmethod
    def _check_repo_type( repos, caller):
        if isinstance(repos, str):
            repos = [repos]
        elif not isinstance(repos, list):
            self._error(2, "%s(), Unsupported input type: %s" %(caller, str(type(repos))))
            return []
        return repos


    def delete_repo(self, repos):
        """delete the selected repo from the system
        
       @type repos: list
        @param repos: ['repo-id1', ...]
        @param output: method to handle output if desired
        @rtype dict
        """
        repos = self._check_repo_type(repos, "delete_repo")
        results = []
        for id in repos:
            if not self.is_installed(id):
                results.append(True)
                break
            if not self.is_repo(id):
                self._error(1, UNKNOWN_REPO_ID %id)
                results.append(False)
                break
            try:
                self._installed_db.delete(self._installed_db.select(id))
                results.append(True)
            except Exception, e:
                self._error(ERROR_INTERNAL_ERROR,
                        "Failed to disable repository '"+id+"':\n"+str(e))
                results.append(False)
            self.get_installed(reload=True)
        if False in results:
            return False
        return True


    def add_repo(self, repos):
        """installs the seleted repo id
        
        @type repos: list
        @param repos: ['repo-id1', ...]
        @param output: method to handle output if desired
        @rtype dict
        """
        repos = self._check_repo_type(repos, "add_repo")
        results = []
        for id in repos:
            if self.is_installed(id):
                results.append(True)
                break
            if not self.is_repo(id):
                self._error(1, UNKNOWN_REPO_ID %id)
                results.append(False)
                break
            try:
                self._installed_db.add(self._available_db.select(id), quiet=True)
                results.append(True)
            except Exception, e:
                self._error(ERROR_INTERNAL_ERROR,
                        "Failed to enable repository '"+id+"' : "+str(e))
                results.append(False)
            self.get_installed(reload=True)
        if False in results:
            return False
        return True


    def get_info(self, repos):
        """retirves the recorded information about the repo specified by id
        
        @type repos: list
        @param repos: ['repo-id1', ...]
        @rtype list of tuples [(str, bool, bool),...]
        @return: dictionary  {'id': (info, official, supported)}
        """
        repos = self._check_repo_type(repos, "get_info")
        result = {}

        for id in repos:
            if not self.is_repo(id):
                self._error(1, UNKNOWN_REPO_ID %id)
                result[id] = ('', False, False))
            try:
                overlay = self._available_db.select(id)
            except UnknownOverlayException, error:
                self._error(2, "Error: %s" %str(error))
                 result[id] = ('', False, False))
            else:
                # Is the overlay supported?
                info = overlay.__str__()
                official = overlay.is_official()
                supported = overlay.is_supported()
                 result[id] = (info, official, supported)

        return result


    def sync(self, repos, output_results=True):
        """syncs the specified repo(s) specified by repos
        
        @type repos: list or string
        @param repos: ['repo-id1', ...] or 'repo-id'
        @rtype bool or {'repo-id': bool,...}
        """
        fatal = []
        warnings = []
        success  = []
        repos = self._check_repo_type(repos, "sync")

        for id in repos:
            try:
                odb = self._installed_db.select(id)
            except UnknownOverlayException, error:
                self._error(1,"Sync(), failed to select %s overlay.  Original error was: %s" %(id, str(error)))
                continue

            try:
                ordb = self._available_db.select(id)
            except UnknownOverlayException:
                message = 'Overlay "%s" could not be found in the remote lists.\n'
                        'Please check if it has been renamed and re-add if necessary.' %id
                warnings.append((id, message))
            else:
                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' % (id + 1, v)) for id, v in enumerate(available_srcs))

                    warnings.append((id,
                        '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':id,
                            'current_src':current_src,
                            'candidates':candidates,
                            'plural':plural,
                            }))

            try:
                self._installed_db.sync(id, self.config['quiet'])
                success.append((id,'Successfully synchronized overlay "' + id + '".'))
            except Exception, error:
                fatals.append((id,
                    'Failed to sync overlay "' + id + '".\nError was: '
                    + str(error)))

        if output_results:
            if success:
                self.output.info('\nSuccess:\n------\n', 3)
                for result in success:
                    self.output.info(result, 3)
                    
            if warnings:
                self.output.warn('\nWarnings:\n------\n', 2)
                for result in warnings:
                    self.output.warn(result + '\n', 2)

            if fatals:
                self.output.error('\nErrors:\n------\n')
                for result in fatals:
                    self.output.error(result + '\n')
                return False
        else:
            self.sync_results = (success, warnings, fatals)

        return True


    def fetch_remote_list(self):
        """Fetches the latest remote overlay list"""
        try:
            self._available_db.cache()
        except Exception, error:
            self._error(-1,'Failed to fetch overlay list!\n Original Error was: '
                    + str(error))
            return False
        return True


    def get_available(self, reload=False):
        """returns the list of available overlays"""
        if not self._available_db or reload:
            self._available_db = RemoteDB(self.config)
            self._available_ids = sorted(self._available_db.overlays)
        return self._available_ids[:]


    def get_installed(self, reload=False):
        """returns the list of installed overlays"""
        if not self._installed_db or reload:
            self._installed_db = DB(self.config)
            self._installed_ids = sorted(self._installed_db.overlays)
        return self._installed_ids[:]


    def reload(self):
        """reloads the installed and remote db's to the data on disk"""
        result = self.get_available(reload=True)
        result = self.get_installed(reload=True)


    def _error(self, num, message):
        """outputs the error to the pre-determined output
        defaults to stderr.  This method may be removed, is here for now
        due to code taken from the packagekit backend.
        """
        m = "Error: %d," %num, message
        self._error_messages.append(m)
        if self.report_errors:
            print >>stderr, m


    def get_errors(self):
        """returns any warning or fatal messages that occurred during
        an operation and resets it back to None
        """
        if self._error_messages:
            return self._error_messages[:]
            self._error_messages = []


class Output(Message):
    """a subclass of debug.py's Message to overide several output functions
    for data capture.  May not be in final api"""
    
    def __init__(self, error=stderr):
        self.stderr = error
        self.captured = []
        Message.__init__(self, err=error)

    def notice (self, note):
        self.captured.append(note)

    def info (self, info, level = 4):

        if type(info) not in types.StringTypes:
            info = str(info)

        if level > self.info_lev:
            return

        for i in info.split('\n'):
            self.captured.append(self.maybe_color('green', '* ') + i)

    def status (self, message, status, info = 'ignored'):

        if type(message) not in types.StringTypes:
            message = str(message)

        lines = message.split('\n')

        if not lines:
            return

        for i in lines[0:-1]:
            self.captured.append(self.maybe_color('green', '* ') + i)

        i = lines[-1]

        if len(i) > 58:
            i = i[0:57]

        if status == 1:
            result = '[' + self.maybe_color('green', 'ok') + ']'
        elif status == 0:
            result = '[' + self.maybe_color('red', 'failed') + ']'
        else:
            result = '[' + self.maybe_color('yellow', info) + ']'

        self.captured.append( self.maybe_color('green', '* ') + i + ' ' + '.' * (58 - len(i))  \
              + ' ' + result)

    def warn (self, warn, level = 4):

        if type(warn) not in types.StringTypes:
            warn = str(warn)

        if level > self.warn_lev:
            return

        for i in warn.split('\n'):
            self.captured.append(self.maybe_color('yellow', '* ') + i)


def create_fd():
    """creates file descriptor pairs an opens them ready for
    use in place of stdin, stdout, stderr.
    """
    fd_r, fd_w = os.pipe()
    w = os.fdopen(fd_w, 'w')
    r = os.fdopen(fd_r, 'r')
    return (r, w, fd_r, fd_w)