summaryrefslogtreecommitdiffstats
path: root/bitbake/lib/bb/ui/crumbs/configurator.py
blob: 587a6ff12997960c38eb42e2dfa4ccb8735df436 (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
#
# BitBake Graphical GTK User Interface
#
# Copyright (C) 2011        Intel Corporation
#
# Authored by Joshua Lock <josh@linux.intel.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import gobject
import copy
import re, os
from bb import data

class Configurator(gobject.GObject):

    """
    A GObject to handle writing modified configuration values back
    to conf files.
    """
    __gsignals__ = {
        "layers-loaded"  : (gobject.SIGNAL_RUN_LAST,
                           gobject.TYPE_NONE,
                           ()),
        "layers-changed" : (gobject.SIGNAL_RUN_LAST,
                            gobject.TYPE_NONE,
                            ())
    }

    def __init__(self):
        gobject.GObject.__init__(self)
        self.local = None
        self.bblayers = None
        self.enabled_layers = {}
        self.loaded_layers = {}
        self.config = {}
        self.orig_config = {}

    # NOTE: cribbed from the cooker...
    def _parse(self, f, data, include=False):
        try:
            return bb.parse.handle(f, data, include)
        except (IOError, bb.parse.ParseError) as exc:
            parselog.critical("Unable to parse %s: %s" % (f, exc))
            sys.exit(1)

    def _loadLocalConf(self, path):
        def getString(var):
            return bb.data.getVar(var, data, True) or ""

        self.local = path

        if self.orig_config:
            del self.orig_config
            self.orig_config = {}

        data = bb.data.init()
        data = self._parse(self.local, data)

        # We only need to care about certain variables
        mach = getString('MACHINE')
        if mach and mach != self.config.get('MACHINE', ''):
            self.config['MACHINE'] = mach
        sdkmach = getString('SDKMACHINE')
        if sdkmach and sdkmach != self.config.get('SDKMACHINE', ''):
            self.config['SDKMACHINE'] = sdkmach
        distro = getString('DISTRO')
        if distro and distro != self.config.get('DISTRO', ''):
            self.config['DISTRO'] = distro
        bbnum = getString('BB_NUMBER_THREADS')
        if bbnum and bbnum != self.config.get('BB_NUMBER_THREADS', ''):
            self.config['BB_NUMBER_THREADS'] = bbnum
        pmake = getString('PARALLEL_MAKE')
        if pmake and pmake != self.config.get('PARALLEL_MAKE', ''):
            self.config['PARALLEL_MAKE'] = pmake
        pclass = getString('PACKAGE_CLASSES')
        if pclass and pclass != self.config.get('PACKAGE_CLASSES', ''):
            self.config['PACKAGE_CLASSES'] = pclass
        fstypes = getString('IMAGE_FSTYPES')
        if fstypes and fstypes != self.config.get('IMAGE_FSTYPES', ''):
            self.config['IMAGE_FSTYPES'] = fstypes

        # Values which aren't always set in the conf must be explicitly
        # loaded as empty values for save to work
        incompat = getString('INCOMPATIBLE_LICENSE')
        if incompat and incompat != self.config.get('INCOMPATIBLE_LICENSE', ''):
            self.config['INCOMPATIBLE_LICENSE'] = incompat
        else:
            self.config['INCOMPATIBLE_LICENSE'] = ""

        self.orig_config = copy.deepcopy(self.config)

    def setLocalConfVar(self, var, val):
        self.config[var] = val

    def getLocalConfVar(self, var):
        if var in self.config:
            return self.config[var]
        else:
            return ""

    def _loadLayerConf(self, path):
        self.bblayers = path
        self.enabled_layers = {}
        self.loaded_layers = {}
        data = bb.data.init()
        data = self._parse(self.bblayers, data)
        layers = (bb.data.getVar('BBLAYERS', data, True) or "").split()
        for layer in layers:
            # TODO: we may be better off calling the layer by its
            # BBFILE_COLLECTIONS value?
            name = self._getLayerName(layer)
            self.loaded_layers[name] = layer

        self.enabled_layers = copy.deepcopy(self.loaded_layers)
        self.emit("layers-loaded")

    def _addConfigFile(self, path):
        pref, sep, filename = path.rpartition("/")
        if filename == "local.conf" or filename == "hob.local.conf":
            self._loadLocalConf(path)
        elif filename == "bblayers.conf":
            self._loadLayerConf(path)

    def _splitLayer(self, path):
        # we only care about the path up to /conf/layer.conf
        layerpath, conf, end = path.rpartition("/conf/")
        return layerpath

    def _getLayerName(self, path):
        # Should this be the collection name?
        layerpath, sep, name = path.rpartition("/")
        return name

    def disableLayer(self, layer):
        if layer in self.enabled_layers:
            del self.enabled_layers[layer]

    def addLayerConf(self, confpath):
        layerpath = self._splitLayer(confpath)
        name = self._getLayerName(layerpath)
        if name not in self.enabled_layers:
            self.addLayer(name, layerpath)
            return name, layerpath
        else:
            return None, None

    def addLayer(self, name, path):
        self.enabled_layers[name] = path

    def _isLayerConfDirty(self):
        # if a different number of layers enabled to what was
        # loaded, definitely different
        if len(self.enabled_layers) != len(self.loaded_layers):
            return True

        for layer in self.loaded_layers:
            # if layer loaded but no longer present, definitely dirty
            if layer not in self.enabled_layers:
                return True

        for layer in self.enabled_layers:
            # if this layer wasn't present at load, definitely dirty
            if layer not in self.loaded_layers:
                return True
            # if this layers path has changed, definitely dirty
            if self.enabled_layers[layer] != self.loaded_layers[layer]:
                return True

        return False

    def _constructLayerEntry(self):
        """
        Returns a string representing the new layer selection
        """
        layers = self.enabled_layers.copy()
        # Construct BBLAYERS entry
        layer_entry = "BBLAYERS = \" \\\n"
        if 'meta' in layers:
            layer_entry = layer_entry + "  %s \\\n" % layers['meta']
            del layers['meta']
        for layer in layers:
            layer_entry = layer_entry + "  %s \\\n" % layers[layer]
        layer_entry = layer_entry + "  \""

        return "".join(layer_entry)

    def writeLocalConf(self):
        # Dictionary containing only new or modified variables
        changed_values = {}
        for var in self.config:
            val = self.config[var]
            if self.orig_config.get(var, None) != val:
                changed_values[var] = val

        if not len(changed_values):
            return

        # Create a backup of the local.conf
        bkup = "%s~" % self.local
        os.rename(self.local, bkup)

        # read the original conf into a list
        with open(bkup, 'r') as config:
            config_lines = config.readlines()

        new_config_lines = ["\n"]
        for var in changed_values:
            # Convenience function for re.subn(). If the pattern matches
            # return a string which contains an assignment using the same
            # assignment operator as the old assignment.
            def replace_val(matchobj):
                var = matchobj.group(1) # config variable
                op = matchobj.group(2) # assignment operator
                val = changed_values[var] # new config value
                return "%s %s \"%s\"" % (var, op, val)

            pattern = '^\s*(%s)\s*([+=?.]+)(.*)' % re.escape(var)
            p = re.compile(pattern)
            cnt = 0
            replaced = False

            # Iterate over the local.conf lines and if they are a match
            # for the pattern comment out the line and append a new line
            # with the new VAR op "value" entry
            for line in config_lines:
                new_line, replacements = p.subn(replace_val, line)
                if replacements:
                    config_lines[cnt] = "#%s" % line
                    new_config_lines.append(new_line)
                    replaced = True
                cnt = cnt + 1

            if not replaced:
                new_config_lines.append("%s = \"%s\"\n" % (var, changed_values[var]))

        # Add the modified variables
        config_lines.extend(new_config_lines)

        # Write the updated lines list object to the local.conf
        with open(self.local, "w") as n:
            n.write("".join(config_lines))

        del self.orig_config
        self.orig_config = copy.deepcopy(self.config)

    def insertTempBBPath(self, bbpath, bbfiles):
        # Create a backup of the local.conf
        bkup = "%s~" % self.local
        os.rename(self.local, bkup)

        # read the original conf into a list
        with open(bkup, 'r') as config:
            config_lines = config.readlines()

        if bbpath:
            config_lines.append("BBPATH := \"${BBPATH}:%s\"\n" % bbpath)
        if bbfiles:
            config_lines.append("BBFILES := \"${BBFILES} %s\"\n" % bbfiles)

        # Write the updated lines list object to the local.conf
        with open(self.local, "w") as n:
            n.write("".join(config_lines))

    def writeLayerConf(self):
        # If we've not added/removed new layers don't write
        if not self._isLayerConfDirty():
            return

        # This pattern should find the existing BBLAYERS
        pattern = 'BBLAYERS\s=\s\".*\"'

        # Backup the users bblayers.conf
        bkup = "%s~" % self.bblayers
        os.rename(self.bblayers, bkup)

        replacement = self._constructLayerEntry()

        with open(bkup, "r") as f:
            contents = f.read()
            p = re.compile(pattern, re.DOTALL)
            new = p.sub(replacement, contents)

        with open(self.bblayers, "w") as n:
            n.write(new)

        # At some stage we should remove the backup we've created
        # though we should probably verify it first
        #os.remove(bkup)

        # set loaded_layers for dirtiness tracking
        self.loaded_layers = copy.deepcopy(self.enabled_layers)

        self.emit("layers-changed")

    def configFound(self, handler, path):
        self._addConfigFile(path)

    def loadConfig(self, path):
        self._addConfigFile(path)