aboutsummaryrefslogtreecommitdiff
blob: dde116d458120729908e9131bcd1ead51d5f1090 (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
# -*- coding: utf-8 -*-

"""
    description.py
    ~~~~~~~~~~~~~~

    This module implements a Python object with the content of a given
    DESCRIPTION file.

    DESCRIPTION files are basically key/value files with multi-line support.
    The separator is a ':'.

    :copyright: (c) 2009-2010 by Rafael Goncalves Martins
    :license: GPL-2, see LICENSE for more details.
"""

from __future__ import absolute_import

__all__ = [
    'Description',
    'SvnDescription',
    're_depends',
    're_pkg_atom'
]

import os
import re
import shutil
import tempfile

from contextlib import closing

from .config import Config
from .compat import py3k
from .checksum import sha1_compute
from .exception import DescriptionException
from .info import Info

if py3k:
    import urllib.request as urllib
else:
    import urllib2 as urllib

from .log import Log
log = Log('g_octave.description')

conf = Config()

# octave-forge DESCRIPTION's dependencies atoms
re_depends = re.compile(r'^([a-zA-Z0-9-]+) *(\( *([><=]?=?) *([0-9.]+) *\))?')

# we'll use atoms like 'control-1.0.11' for g-octave packages
re_pkg_atom = re.compile(r'^(.+)-([0-9.]+)$') 

class Description(object):

    def __init__(self, file, parse_sysreq=True):
        
        log.info('Parsing file: %s' % file)

        if not os.path.exists(file):
            log.error('File not found: %s' % file)
            raise DescriptionException('File not found: %s' % file)

        self._file = file

        self._info = Info(os.path.join(conf.db, 'info.json'))

        # dictionary with the parsed content of the DESCRIPTION file
        self._desc = dict()

        # current key
        key = None

        with open(file, 'rb') as fp:
            for line in fp:
                
                line = line.decode('iso-8859-15')
                line_splited = line.split(':')

                # 'key: value' found?
                if len(line_splited) >= 2:

                    # by default we have a key before the first ':'
                    key = line_splited[0].strip().lower()

                    # all the stuff after the first ':' is the value
                    # ':' included.
                    value = ':'.join(line_splited[1:]).strip()

                    # the key already exists?
                    if key in self._desc:

                        # it's one of the dependencies?
                        if key in ('depends', 'systemrequirements', 'buildrequires'):

                            # use ', ' to separate the values
                            self._desc[key] += ', '

                        else:

                            # use a single space to separate the values
                            self._desc[key] += ' '

                    # key didn't exists yet. initializing...
                    else:
                        self._desc[key] = ''

                    self._desc[key] += value

                # it's not a 'key: value', so it's probably a continuation
                # of the previous line.
                else:

                    # empty line
                    if len(line) == 0:
                        continue

                    # comments (started with '#')
                    if line[0] == '#':
                        continue

                    # line continuations starts with a single space
                    if line[0] != ' ':
                        continue

                    # the first line can't be a continuation, obviously :)
                    if key is None:
                        continue

                    # our line already have a single space at the start.
                    # we only needs strip spaces at the end of the line
                    self._desc[key] += line.rstrip()

        # add the 'self_depends' key
        self._desc['self_depends'] = list()
        
        # add the 'gentoo_license' key
        self._desc['license_gentoo'] = ''

        # parse the dependencies and license
        for key in self._desc:

            # depends
            if key == 'depends':
                depends = self._desc[key]
                self._desc[key] = self._parse_depends(depends)
                self._desc['self_depends'] = self._parse_self_depends(depends)

            # requirements
            if key in ('systemrequirements', 'buildrequires') and parse_sysreq:
                self._desc[key] = self._parse_depends(self._desc[key])
            
            # license
            if key == 'license':
                try:
                    new_license = self._info.licenses.get(self._desc['license'])
                except:
                    new_license = ''
                if new_license not in [None, '']:
                    self._desc['license_gentoo'] = new_license
                else:
                    self._desc['license_gentoo'] = self._desc['license']


    def _parse_depends(self, depends):
        """returns a list with gentoo atoms for the 'depends' (the other
        octave-forge packages or the octave itself)
        """

        # the list that will be returned
        depends_list = list()

        for depend in depends.split(','):

            # use the 're_depends' regular expression to filter the
            # package name, the version an the comparator
            re_match = re_depends.match(depend.strip())

            # the depend is valid?
            if re_match is not None:

                # initialize the atom string empty
                atom = ''

                # extract the needed values
                name = re_match.group(1)
                comparator = re_match.group(3)
                version = re_match.group(4)

                # we have a comparator and a version?
                if comparator is not None and version is not None:

                    # special case: '==' for octave forge is '=' for gentoo
                    if comparator == '==':
                        atom += '='
                    else:
                        atom += comparator

                # as octave is already in the portage tree, the atom is
                # predefined.
                if name.lower() == 'octave':
                    atom += 'sci-mathematics/octave'

                elif name in self._info.dependencies:
                    if self._info.dependencies[name] == '':
                        continue
                    atom += self._info.dependencies[name]

                # the octave-forge packages will be put inside a "fake"
                # category: g-octave
                else:
                    atom += 'g-octave/' + str(name)

                # append the version to the atom, if needed
                if comparator is not None and version is not None:
                    atom += '-' + str(version)

                depends_list.append(atom)

            # invalid dependency atom
            else:
                log.error('Invalid dependency atom: %s' % depend)
                raise DescriptionException('Invalid dependency atom: %s' % depend)

        return list(set(depends_list))


    def _parse_self_depends(self, depends):
        """returns a list of tuples (name, comparator, version) for the
        other octave-forge packages.
        """

        # the list that will be returned
        depends_list = list()

        for depend in depends.split(','):

            # use the 're_depends' regular expression to filter the
            # package name, the version an the comparator
            re_match = re_depends.match(depend.strip())

            # the depend is valid?
            if re_match is not None:

                # extract the needed values
                name = re_match.group(1)
                comparator = re_match.group(3)
                version = re_match.group(4)

                # we need only the octave-forge packages, nor octave
                if name.lower() != 'octave':
                    depends_list.append((name, comparator, version))

            # invalid dependency atom
            else:
                log.error('Invalid dependency atom: %s' % depend)
                raise DescriptionException('Invalid dependency atom: %s' % depend)

        return depends_list


    def sha1sum(self):
        return sha1_compute(self._file)


    def __getattr__(self, name):
        """method that overloads the object atributes, returning the needed
        atribute based on the dict with the previously parsed content.
        """

        return self._desc.get(name, None)


class SvnDescription(Description):
    
    _url = 'https://octave.svn.sourceforge.net/svnroot/octave/trunk/octave-forge'
    
    def __init__(self, category, package):
        temp_desc = config_file = tempfile.mkstemp()[1]
        desc_url = '%s/%s/%s/DESCRIPTION' % (
            self._url,
            category,
            package,
        )
        try:
            with closing(urllib.urlopen(desc_url)) as fp:
                with open(temp_desc, 'wb') as fp_:
                    shutil.copyfileobj(fp, fp_)
        except:
            raise DescriptionException('Failed to fetch DESCRIPTION file from SVN')
        Description.__init__(self, temp_desc)
        os.unlink(temp_desc)