Subversion Repositories HelenOS-historic

Rev

Rev 555 | Rev 558 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
545 palkovsky 1
#!/usr/bin/env python
2
"""
3
Kernel configuration script
4
"""
5
import sys
6
import os
7
import re
8
 
9
INPUT = 'kernel.config'
10
OUTPUT = 'Makefile.config'
11
TMPOUTPUT = 'Makefile.config.tmp'
12
 
13
class DefaultDialog:
14
    "Wrapper dialog that tries to return default values"
15
    def __init__(self, dlg):
16
        self.dlg = dlg
17
 
18
    def set_title(self,text):
19
        self.dlg.set_title(text)
20
 
21
    def yesno(self, text, default=None):
22
        if default is not None:
23
            return default
24
        return self.dlg.yesno(text, default)
25
    def noyes(self, text, default=None):
26
        if default is not None:
27
            return default
28
        return self.dlg.noyes(text, default)
29
 
30
    def choice(self, text, choices, defopt=None):
31
        if defopt is not None:
32
            return choices[defopt][0]
33
        return self.dlg.choice(text, choices, defopt)
34
 
35
class NoDialog:
36
    def __init__(self):
37
        self.printed = None
38
        self.title = 'HelenOS Configuration'
39
 
40
    def print_title(self):
41
        if not self.printed:
552 palkovsky 42
            sys.stdout.write("\n*** %s ***\n" % self.title)
545 palkovsky 43
            self.printed = True
44
 
45
    def set_title(self, text):
46
        self.title = text
47
        self.printed = False
48
 
49
    def noyes(self, text, default=None):
50
        if not default:
51
            default = 'n'
52
        return self.yesno(text, default)
53
 
54
    def yesno(self, text, default=None):
55
        self.print_title()
56
 
57
        if default != 'n':
58
            default = 'y'
59
        while 1:
60
            sys.stdout.write("%s (y/n)[%s]: " % (text,default))
61
            inp = sys.stdin.readline()
62
            if not inp:
63
                raise EOFError
64
            inp = inp.strip().lower()
65
            if not inp:
66
                return default
67
            if inp == 'y':
68
                return 'y'
69
            elif inp == 'n':
70
                return 'n'
71
 
72
    def _print_choice(self, text, choices, defopt):
73
        sys.stdout.write('%s:\n' % text)
74
        for i,(text,descr) in enumerate(choices):
75
            sys.stdout.write('\t%2d. %s\n' % (i, descr))
76
        if defopt is not None:
77
            sys.stdout.write('Enter choice number[%d]: ' % defopt)
78
        else:
79
            sys.stdout.write('Enter choice number: ')
554 palkovsky 80
 
81
    def menu(self, text, choices, button, defopt=None):
555 palkovsky 82
        menu = []
83
        for key, descr in choices:
84
            txt = key + (45-len(key))*' ' + ': ' + descr
85
            menu.append((key, txt))
86
 
87
        return self.choice(text, [button] + menu)
545 palkovsky 88
 
89
    def choice(self, text, choices, defopt=None):
90
        self.print_title()
91
        while 1:
92
            self._print_choice(text, choices, defopt)
93
            inp = sys.stdin.readline()
94
            if not inp:
95
                raise EOFError
96
            if not inp.strip():
97
                if defopt is not None:
98
                    return choices[defopt][0]
99
                continue
100
            try:
101
                number = int(inp.strip())
102
            except ValueError:
103
                continue
104
            if number < 0 or number >= len(choices):
105
                continue
106
            return choices[number][0]
107
 
108
 
109
class Dialog(NoDialog):
110
    def __init__(self):
111
        NoDialog.__init__(self)
112
        self.dlgcmd = os.environ.get('DIALOG','dialog')
554 palkovsky 113
        self.title = ''
114
        self.backtitle = 'HelenOS Kernel Configuration'
545 palkovsky 115
 
116
        if os.system('%s --print-maxsize >/dev/null 2>&1' % self.dlgcmd) != 0:
117
            raise NotImplementedError
118
 
119
    def set_title(self,text):
120
        self.title = text
121
 
122
    def calldlg(self,*args,**kw):
549 palkovsky 123
        "Wrapper for calling 'dialog' program"
545 palkovsky 124
        indesc, outdesc = os.pipe()
125
        pid = os.fork()
126
        if not pid:
127
            os.close(2)
128
            os.dup(outdesc)
129
            os.close(indesc)
130
 
554 palkovsky 131
            dlgargs = [self.dlgcmd,'--title',self.title,
132
                       '--backtitle', self.backtitle]
545 palkovsky 133
            for key,val in kw.items():
134
                dlgargs.append('--'+key)
135
                dlgargs.append(val)
136
            dlgargs += args            
137
            os.execlp(self.dlgcmd,*dlgargs)
138
 
139
        os.close(outdesc)
140
        errout = os.fdopen(indesc,'r')
141
        data = errout.read()
142
        errout.close()
143
 
144
        pid,status = os.wait()
145
        if not os.WIFEXITED(status):
146
            raise EOFError
147
        status = os.WEXITSTATUS(status)
148
        if status == 255:
149
            raise EOFError
150
        return status,data
151
 
152
    def yesno(self, text, default=None):
153
        text = text + ':'
154
        width = '50'
155
        height = '5'
156
        if len(text) < 48:
157
            text = ' '*int(((48-len(text))/2)) + text
158
        else:
159
            width = '0'
160
            height = '0'
161
        if default == 'n':
162
            res,data = self.calldlg('--defaultno','--yesno',text,height,width)
163
        else:
164
            res,data = self.calldlg('--yesno',text,height,width)
165
 
166
        if res == 0:
167
            return 'y'
168
        return 'n'
554 palkovsky 169
 
170
    def menu(self, text, choices, button, defopt=None):
171
        text = text + ':'
172
        width = '70'
173
        height = str(8 + len(choices))
174
        args = []
175
        for key,val in choices:
176
            args.append(key)
177
            args.append(val)
178
 
179
        kw = {}
180
        if defopt:
181
            kw['default-item'] = choices[defopt][0]
182
        res,data = self.calldlg('--cancel-label',button[1],
183
                                '--menu',text,height,width,
184
                                str(len(choices)),*args,**kw)
185
        if res == 1:
186
            return button[0]
187
        elif res:
188
            print data
189
            raise EOFError
190
        return data
545 palkovsky 191
 
192
    def choice(self, text, choices, defopt=None):
193
        text = text + ':'
194
        width = '50'
195
        height = str(8 + len(choices))
196
        args = []
197
        for key,val in choices:
198
            args.append(key)
199
            args.append(val)
200
 
201
        kw = {}
202
        if defopt:
203
            kw['default-item'] = choices[defopt][0]
204
        res,data = self.calldlg('--nocancel','--menu',text,height,width,
205
                                str(len(choices)),*args, **kw)
206
        if res:
207
            print data
208
            raise EOFError
209
        return data
210
 
547 palkovsky 211
def read_defaults(fname,defaults):
549 palkovsky 212
    "Read saved values from last configuration run"
545 palkovsky 213
    f = file(fname,'r')
214
    for line in f:
547 palkovsky 215
        res = re.match(r'^(?:#!# )?([^#]\w*)\s*=\s*(.*?)\s*$', line)
545 palkovsky 216
        if res:
217
            defaults[res.group(1)] = res.group(2)
218
    f.close()
219
 
547 palkovsky 220
def check_condition(text, defaults):
550 palkovsky 221
    result = True
222
    conds = text.split('&')
223
    for cond in conds:
224
        if cond.startswith('(') and cond.endswith(')'):
225
            cond = cond[1:-1]
226
        if not check_dnf(cond, defaults):
227
            return False
228
    return True
229
 
230
def check_dnf(text, defaults):
231
    """
232
    Check that the condition specified on input line is True
233
 
234
    only CNF is supported
235
    """
547 palkovsky 236
    conds = text.split('|')
237
    for cond in conds:
550 palkovsky 238
        res = re.match(r'^(.*?)(!?=)(.*)$', cond)
239
        if not res:
240
            raise RuntimeError("Invalid condition: %s" % cond)
241
        condname = res.group(1)
242
        oper = res.group(2)
243
        condval = res.group(3)
547 palkovsky 244
        if not defaults.has_key(condname):
245
            raise RuntimeError("Condition var %s does not exist: %s" % \
550 palkovsky 246
                               (condname,text))
247
 
248
        if oper=='=' and  condval == defaults[condname]:
547 palkovsky 249
            return True
550 palkovsky 250
        if oper == '!=' and condval != defaults[condname]:
547 palkovsky 251
            return True
252
    return False
253
 
554 palkovsky 254
def parse_config(input, output, dlg, defaults={}, askonly=None):
549 palkovsky 255
    "Parse configuration file and create Makefile.config on the fly"
556 palkovsky 256
    def ask_the_question():
257
        "Ask question based on the type of variables to ask"
258
        # This is quite a hack, this thingy is written just to
259
        # have access to local variables..
260
        if vartype == 'y/n':
261
            return dlg.yesno(comment, default)
262
        elif vartype == 'n/y':
263
            return dlg.noyes(comment, default)
264
        elif vartype == 'choice':
265
            defopt = None
266
            if default is not None:
267
                for i,(key,val) in enumerate(choices):
268
                    if key == default:
269
                        defopt = i
270
                        break
271
            return dlg.choice(comment, choices, defopt)
272
        else:
273
            raise RuntimeError("Bad method: %s" % vartype)
274
 
275
 
545 palkovsky 276
    f = file(input, 'r')
277
    outf = file(output, 'w')
278
 
279
    outf.write('#########################################\n')
280
    outf.write('## AUTO-GENERATED FILE, DO NOT EDIT!!! ##\n')
281
    outf.write('#########################################\n\n')
282
 
554 palkovsky 283
    asked_names = []
284
 
545 palkovsky 285
    comment = ''
286
    default = None
287
    choices = []
550 palkovsky 288
    for line in f:
289
        if line.startswith('%'):
290
            res = re.match(r'^%\s*(?:\[(.*?)\])?\s*(.*)$', line)
291
            if not res:
292
                raise RuntimeError('Invalid command: %s' % line)
293
            if res.group(1):
294
                if not check_condition(res.group(1), defaults):
295
                    continue
296
            args = res.group(2).strip().split(' ')
297
            cmd = args[0].lower()
298
            args = args[1:]
554 palkovsky 299
            if cmd == 'saveas':
550 palkovsky 300
                outf.write('%s = %s\n' % (args[1],defaults[args[0]]))
301
 
302
            continue
303
 
545 palkovsky 304
        if line.startswith('!'):
549 palkovsky 305
            # Ask a question
547 palkovsky 306
            res = re.search(r'!\s*(?:\[(.*?)\])?\s*([^\s]+)\s*\((.*)\)\s*$', line)
545 palkovsky 307
            if not res:
308
                raise RuntimeError("Weird line: %s" % line)
547 palkovsky 309
            varname = res.group(2)
310
            vartype = res.group(3)
545 palkovsky 311
 
312
            default = defaults.get(varname,None)
554 palkovsky 313
 
547 palkovsky 314
            if res.group(1):
315
                if not check_condition(res.group(1), defaults):
316
                    if default is not None:
317
                        outf.write('#!# %s = %s\n' % (varname, default))
550 palkovsky 318
                    # Clear cumulated values
319
                    comment = ''
320
                    default = None
321
                    choices = []
547 palkovsky 322
                    continue
554 palkovsky 323
 
324
            asked_names.append((varname,comment))
547 palkovsky 325
 
556 palkovsky 326
            if default is None or not askonly or askonly == varname:
327
                default = ask_the_question()
554 palkovsky 328
 
556 palkovsky 329
            outf.write('%s = %s\n' % (varname, default))
547 palkovsky 330
            # Remeber the selected value
556 palkovsky 331
            defaults[varname] = default
545 palkovsky 332
            # Clear cumulated values
333
            comment = ''
334
            default = None
335
            choices = []
336
            continue
337
 
338
        if line.startswith('@'):
549 palkovsky 339
            # Add new line into the 'choice array' 
547 palkovsky 340
            res = re.match(r'@\s*(?:\[(.*?)\])?\s*"(.*?)"\s*(.*)$', line)
545 palkovsky 341
            if not res:
342
                raise RuntimeError("Bad line: %s" % line)
547 palkovsky 343
            if res.group(1):
344
                if not check_condition(res.group(1),defaults):
345
                    continue
346
            choices.append((res.group(2), res.group(3)))
545 palkovsky 347
            continue
549 palkovsky 348
 
349
        # All other things print to output file
545 palkovsky 350
        outf.write(line)
351
        if re.match(r'^#[^#]', line):
549 palkovsky 352
            # Last comment before question will be displayed to the user
545 palkovsky 353
            comment = line[1:].strip()
552 palkovsky 354
        elif line.startswith('## '):
549 palkovsky 355
            # Set title of the dialog window
545 palkovsky 356
            dlg.set_title(line[2:].strip())
357
 
358
    outf.close()
359
    f.close()
554 palkovsky 360
    return asked_names
545 palkovsky 361
 
362
def main():
550 palkovsky 363
    defaults = {}
545 palkovsky 364
    try:
365
        dlg = Dialog()
366
    except NotImplementedError:
367
        dlg = NoDialog()
368
 
554 palkovsky 369
    if len(sys.argv) == 2 and sys.argv[1]=='default':
370
        defmode = True
371
    else:
372
        defmode = False
373
 
545 palkovsky 374
    # Default run will update the configuration file
375
    # with newest options
376
    if os.path.exists(OUTPUT):
547 palkovsky 377
        read_defaults(OUTPUT, defaults)
555 palkovsky 378
 
379
    # Dry run only with defaults
554 palkovsky 380
    varnames = parse_config(INPUT, TMPOUTPUT, DefaultDialog(dlg), defaults)
381
    # If not in default mode, present selection of all possibilities
382
    if not defmode:
383
        defopt = 0
384
        while 1:
555 palkovsky 385
            # varnames contains variable names that were in the
386
            # last question set
554 palkovsky 387
            choices = [ (x[1],defaults[x[0]]) for x in varnames ]
388
            res = dlg.menu('Configuration',choices,('save','Save'),defopt)
389
            if res == 'save':
390
                parse_config(INPUT, TMPOUTPUT, DefaultDialog(dlg), defaults)
391
                break
392
            # transfer description back to varname
393
            for i,(vname,descr) in enumerate(varnames):
394
                if res == descr:
395
                    defopt = i
396
                    break
555 palkovsky 397
            # Ask the user a simple question, produce output
398
            # as if the user answered all the other questions
399
            # with default answer
554 palkovsky 400
            varnames = parse_config(INPUT, TMPOUTPUT, dlg, defaults,
401
                                    askonly=varnames[i][0])
402
 
403
 
545 palkovsky 404
    if os.path.exists(OUTPUT):
405
        os.unlink(OUTPUT)
406
    os.rename(TMPOUTPUT, OUTPUT)
407
 
408
 
409
if __name__ == '__main__':
410
    main()