summaryrefslogtreecommitdiff
path: root/ybd/morphs.py
blob: 4e1059dd04fd60938105541d7330af36a43b98ac (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
# Copyright (C) 2014-2016  Codethink Limited
#
# 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; version 2 of the License.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-2 =*=

import yaml
import os
from app import chdir, config, log
from defaults import Defaults


def is_not_hidden_dir(d):
    return not d.startswith('.')


class Morphs(object):

    def __init__(self, directory='.'):
        '''Load all definitions from a directory tree.'''
        self._data = {}
        self.defaults = Defaults()
        self.fields = self.defaults.build_steps + self.defaults.fields

        with chdir(directory):
            for outer_dirname, dirnames, filenames in os.walk('.'):
                dirnames[:] = filter(is_not_hidden_dir, dirnames)
                filenames.sort()
                dirnames.sort()
                for filename in filenames:
                    if filename.endswith('.morph'):
                        path = os.path.join(outer_dirname, filename)
                        data = self._load(path)
                        if data is not None:
                            data['path'] = self._demorph(path[2:])
                            self._fix_keys(data)
                            self._tidy_and_insert_recursively(data)

        for x in self._data:
            dn = self._data[x]
            for field in dn:
                if field not in self.fields:
                    log(dn, 'Invalid field "%s" in' % field, dn['path'],
                        exit=True)

    def _load(self, path):
        '''Load a single definition file as a dict.

        The file is assumed to be yaml, and we insert the provided path into
        the dict keyed as 'path'.

        '''
        try:
            with open(path) as f:
                text = f.read()
            contents = yaml.safe_load(text)
        except yaml.YAMLError, exc:
            log('DEFINITIONS', 'Could not parse %s' % path, exc, exit=True)

        if type(contents) is not dict:
            log('DEFINITIONS', 'WARNING: %s contents is not dict:' % path,
                str(contents)[0:50])
            return None
        return contents

    def _tidy_and_insert_recursively(self, dn):
        '''Insert a definition and its contents into the dictionary.

        Takes a dict containing the content of a definition file.

        Inserts the definitions referenced or defined in the
        'build-depends' and 'contents' keys of `definition` into the
        dictionary, and then inserts `definition` itself into the
        dictionary.

        '''
        # handle morph syntax oddities...
        for index, component in enumerate(dn.get('build-depends', [])):
            self._fix_keys(component)
            dn['build-depends'][index] = self._insert(component)

        # The 'contents' field in the internal data model corresponds to the
        # 'chunks' field in a stratum .morph file, or the 'strata' field in a
        # system .morph file.
        dn['contents'] = dn.get('contents', [])

        if type(dn.get('chunks', [])) is not list:
            log('DEFINITIONS', 'WARNING: %s chunks must be list:' % dn['path'],
                dn.get('chunks', []), exit=True)

        if type(dn.get('strata', [])) is not list:
            log('DEFINITIONS', 'WARNING: %s strata must be list:' % dn['path'],
                dn.get('strata', []), exit=True)

        dn['contents'] += dn.pop('chunks', []) + dn.pop('strata', [])

        lookup = {}
        for index, component in enumerate(dn['contents']):
            self._fix_keys(component, dn['path'])
            lookup[component['name']] = component['path']
            if component['name'] == dn['name']:
                log(dn, 'WARNING: %s contains' % dn['path'], dn['name'])

            for x, it in enumerate(component.get('build-depends', [])):
                if it not in lookup:
                    # it is defined as a build depend, but hasn't actually been
                    # defined yet...
                    dependency = {'name': it}
                    self._fix_keys(dependency,  dn['path'])
                    lookup[it] = dependency['path']
                component['build-depends'][x] = lookup[it]

            component['build-depends'] = (dn.get('build-depends', []) +
                                          component.get('build-depends', []))

            if config.get('artifact-version', 0) not in range(0, 5):
                c = self._data.get(component['path'])
                if c and 'build-depends' in c:
                    component['build-depends'] += c['build-depends']

            splits = component.get('artifacts', [])
            dn['contents'][index] = {self._insert(component): splits}

        return self._insert(dn)

    def _fix_keys(self, dn, base=None):
        '''Normalizes keys for a definition dict and its contents

        Some definitions have a 'morph' field which is a relative path. Others
        only have a 'name' field, which has no directory part. A few do not
        have a 'name'

        This sets our key to be 'path', and fixes any missed 'name' to be
        the same as 'path' but replacing '/' by '-'

        '''

        exit = (config.get('check-definitions') == 'exit')

        if dn.get('morph'):
            if not os.path.isfile(dn.get('morph')):
                log('DEFINITION', 'WARNING: missing', dn['morph'], exit=exit)
            dn['path'] = self._demorph(dn.pop('morph'))

        if 'path' not in dn:
            if 'name' not in dn:
                log(dn, 'No path, no name?', exit=True)
            if config.get('artifact-version', 0) in range(0, 4):
                dn['path'] = dn['name']
            else:
                dn['path'] = os.path.join(self._demorph(base), dn['name'])
                if os.path.isfile(dn['path'] + '.morph'):
                    # morph file exists, but is not mentioned in stratum
                    # so we ignore it
                    log(dn, 'WARNING: ignoring', dn['path'] + '.morph',
                        exit=exit)
                    dn['path'] += '.default'

        dn['path'] = self._demorph(dn['path'])
        dn.setdefault('name', os.path.basename(dn['path']))

        if dn.get('name') == config['target']:
            config['target'] = dn['path']

        n = self._demorph(os.path.basename(dn['name']))
        p = self._demorph(os.path.basename(dn['path']))
        if os.path.splitext(p)[0] not in n:
            log('MORPHS', 'WARNING: %s wrong name' % dn['path'], dn['name'],
                exit=exit)

        for system in (dn.get('systems', []) + dn.get('subsystems', [])):
            self._fix_keys(system)

    def _insert(self, new_def):
        '''Insert a new definition into the dictionary, return the key.

        Takes a dict representing a single definition.

        If a definition with the same 'path' doesn't exist, just add
        `new_def` to the dictionary.

        If a definition with the same 'path' already exists, extend the
        existing definition with the contents of `new_def` unless it
        and the new definition both contain a 'ref'. If any keys are
        duplicated in the existing definition, output a warning.

        If `new_def` contains a sha: field (which needs to be 40 chars),
        this overrides ref:  field

        '''

        exit = (config.get('check-definitions') == 'exit')

        dn = self._data.get(new_def['path'])
        if dn:
            if (dn.get('ref') is None or new_def.get('ref') is None):
                for key in new_def:
                    if key is not 'name':
                        dn[key] = new_def[key]

            if dn['name'] != new_def['name']:
                log(new_def, 'WARNING: %s also named as' % new_def['name'],
                    dn['name'], exit=exit)
                dn['name'] = new_def['name']

            for key in new_def:
                if dn.get(key) and new_def[key] and dn[key] != new_def[key]:
                    log(new_def,
                        'WARNING: multiple definitions of %s \n' % key,
                        '%s | %s' % (dn.get(key), new_def[key]), exit=exit)

        sha = new_def.get('sha')
        if sha:
            if len(sha) != 40:
                log(new_def, 'ERROR: invalid sha:', sha, exit=True)
        if new_def.get('ref'):
            if not sha and len(new_def['ref']) != 40:
                log(new_def, 'WARNING: ref is not a sha:', new_def['ref'],
                    exit=False)
        if new_def.get('unpetrify-ref'):
            log(new_def, 'WARNING: \'unpetrify-ref\' is a deprecated field',
                exit=False)

        if new_def.get('rpm-metadata'):
            # Support two formats of 'rpm-metadata', the older
            # format specifies 'rpm-metadata' as a list of packages,
            # the new format specifies 'rpm-metadata' as a dictionary
            # and the package list is found in it's 'packages' member.
            if isinstance(new_def['rpm-metadata'], list):
                new_def['rpm-metadata'] = {'packages': new_def['rpm-metadata']}

        if dn is None:
            self._data[new_def['path']] = new_def

        return new_def['path']

    def _demorph(self, path):
        if config.get('artifact-version', 0) not in range(0, 4):
            if path.endswith('.morph'):
                path = path.rpartition('.morph')[0]
        return path