source: mainline/tools/config.py@ 8d6d76a

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 8d6d76a was 616f1759, checked in by Ondrej Palkovsky <ondrap@…>, 19 years ago

Fixed bad dialog in config.

  • Property mode set to 100755
File size: 15.5 KB
RevLine 
[34722ee]1#!/usr/bin/env python
2"""
3Kernel configuration script
4"""
5import sys
6import os
7import re
[940cac0]8import commands
[34722ee]9
10INPUT = 'kernel.config'
11OUTPUT = 'Makefile.config'
12TMPOUTPUT = 'Makefile.config.tmp'
13
14class DefaultDialog:
15 "Wrapper dialog that tries to return default values"
16 def __init__(self, dlg):
17 self.dlg = dlg
18
19 def set_title(self,text):
20 self.dlg.set_title(text)
21
22 def yesno(self, text, default=None):
23 if default is not None:
24 return default
25 return self.dlg.yesno(text, default)
26 def noyes(self, text, default=None):
27 if default is not None:
28 return default
29 return self.dlg.noyes(text, default)
30
31 def choice(self, text, choices, defopt=None):
32 if defopt is not None:
33 return choices[defopt][0]
34 return self.dlg.choice(text, choices, defopt)
35
36class NoDialog:
37 def __init__(self):
38 self.printed = None
39 self.title = 'HelenOS Configuration'
40
41 def print_title(self):
42 if not self.printed:
[2d93f1f9]43 sys.stdout.write("\n*** %s ***\n" % self.title)
[34722ee]44 self.printed = True
45
46 def set_title(self, text):
47 self.title = text
48 self.printed = False
49
50 def noyes(self, text, default=None):
51 if not default:
52 default = 'n'
53 return self.yesno(text, default)
54
55 def yesno(self, text, default=None):
56 self.print_title()
57
58 if default != 'n':
59 default = 'y'
60 while 1:
61 sys.stdout.write("%s (y/n)[%s]: " % (text,default))
62 inp = sys.stdin.readline()
63 if not inp:
64 raise EOFError
65 inp = inp.strip().lower()
66 if not inp:
67 return default
68 if inp == 'y':
69 return 'y'
70 elif inp == 'n':
71 return 'n'
72
73 def _print_choice(self, text, choices, defopt):
74 sys.stdout.write('%s:\n' % text)
75 for i,(text,descr) in enumerate(choices):
76 sys.stdout.write('\t%2d. %s\n' % (i, descr))
77 if defopt is not None:
78 sys.stdout.write('Enter choice number[%d]: ' % defopt)
79 else:
80 sys.stdout.write('Enter choice number: ')
[beb39ee3]81
82 def menu(self, text, choices, button, defopt=None):
[96c939e]83 self.title = 'Main menu'
[994cf4b]84 menu = []
85 for key, descr in choices:
86 txt = key + (45-len(key))*' ' + ': ' + descr
87 menu.append((key, txt))
88
89 return self.choice(text, [button] + menu)
[34722ee]90
91 def choice(self, text, choices, defopt=None):
92 self.print_title()
93 while 1:
94 self._print_choice(text, choices, defopt)
95 inp = sys.stdin.readline()
96 if not inp:
97 raise EOFError
98 if not inp.strip():
99 if defopt is not None:
100 return choices[defopt][0]
101 continue
102 try:
103 number = int(inp.strip())
104 except ValueError:
105 continue
106 if number < 0 or number >= len(choices):
107 continue
108 return choices[number][0]
109
110
[616f1759]111def eof_checker(fnc):
112 def wrapper(self, *args, **kw):
113 try:
114 return fnc(self, *args, **kw)
115 except EOFError:
116 return getattr(self.bckdialog,fnc.func_name)(*args, **kw)
117 return wrapper
118
[34722ee]119class Dialog(NoDialog):
120 def __init__(self):
121 NoDialog.__init__(self)
122 self.dlgcmd = os.environ.get('DIALOG','dialog')
[beb39ee3]123 self.title = ''
124 self.backtitle = 'HelenOS Kernel Configuration'
[34722ee]125
126 if os.system('%s --print-maxsize >/dev/null 2>&1' % self.dlgcmd) != 0:
127 raise NotImplementedError
[616f1759]128
129 self.bckdialog = NoDialog()
[34722ee]130
131 def set_title(self,text):
132 self.title = text
[616f1759]133 self.bckdialog.set_title(text)
[34722ee]134
135 def calldlg(self,*args,**kw):
[090e7ea1]136 "Wrapper for calling 'dialog' program"
[34722ee]137 indesc, outdesc = os.pipe()
138 pid = os.fork()
139 if not pid:
140 os.close(2)
141 os.dup(outdesc)
142 os.close(indesc)
143
[beb39ee3]144 dlgargs = [self.dlgcmd,'--title',self.title,
145 '--backtitle', self.backtitle]
[34722ee]146 for key,val in kw.items():
147 dlgargs.append('--'+key)
148 dlgargs.append(val)
149 dlgargs += args
150 os.execlp(self.dlgcmd,*dlgargs)
151
152 os.close(outdesc)
[839470f]153
154 try:
155 errout = os.fdopen(indesc,'r')
156 data = errout.read()
157 errout.close()
158 pid,status = os.wait()
159 except:
160 os.system('reset') # Reset terminal
161 raise
162
[34722ee]163 if not os.WIFEXITED(status):
[839470f]164 os.system('reset') # Reset terminal
[34722ee]165 raise EOFError
[839470f]166
[34722ee]167 status = os.WEXITSTATUS(status)
168 if status == 255:
169 raise EOFError
170 return status,data
171
172 def yesno(self, text, default=None):
[839470f]173 if text[-1] not in ('?',':'):
174 text = text + ':'
[34722ee]175 width = '50'
176 height = '5'
177 if len(text) < 48:
178 text = ' '*int(((48-len(text))/2)) + text
179 else:
180 width = '0'
181 height = '0'
182 if default == 'n':
183 res,data = self.calldlg('--defaultno','--yesno',text,height,width)
184 else:
185 res,data = self.calldlg('--yesno',text,height,width)
186
187 if res == 0:
188 return 'y'
189 return 'n'
[616f1759]190 yesno = eof_checker(yesno)
[beb39ee3]191
192 def menu(self, text, choices, button, defopt=None):
[96c939e]193 self.title = 'Main menu'
[beb39ee3]194 text = text + ':'
195 width = '70'
196 height = str(8 + len(choices))
197 args = []
198 for key,val in choices:
199 args.append(key)
200 args.append(val)
201
202 kw = {}
203 if defopt:
204 kw['default-item'] = choices[defopt][0]
[ac0cb2a]205 res,data = self.calldlg('--ok-label','Change',
206 '--extra-label',button[1],
[45ab770]207 '--extra-button',
[beb39ee3]208 '--menu',text,height,width,
209 str(len(choices)),*args,**kw)
[45ab770]210 if res == 3:
[beb39ee3]211 return button[0]
[45ab770]212 if res == 1: # Cancel
213 sys.exit(1)
[beb39ee3]214 elif res:
215 print data
216 raise EOFError
217 return data
[616f1759]218 menu = eof_checker(menu)
[34722ee]219
220 def choice(self, text, choices, defopt=None):
221 text = text + ':'
222 width = '50'
223 height = str(8 + len(choices))
224 args = []
225 for key,val in choices:
226 args.append(key)
227 args.append(val)
228
229 kw = {}
230 if defopt:
231 kw['default-item'] = choices[defopt][0]
232 res,data = self.calldlg('--nocancel','--menu',text,height,width,
233 str(len(choices)),*args, **kw)
234 if res:
235 print data
236 raise EOFError
237 return data
[616f1759]238 choice = eof_checker(choice)
[34722ee]239
[795ff98]240def read_defaults(fname,defaults):
[090e7ea1]241 "Read saved values from last configuration run"
[34722ee]242 f = file(fname,'r')
243 for line in f:
[795ff98]244 res = re.match(r'^(?:#!# )?([^#]\w*)\s*=\s*(.*?)\s*$', line)
[34722ee]245 if res:
246 defaults[res.group(1)] = res.group(2)
247 f.close()
[795ff98]248
[944b15c]249def check_condition(text, defaults, asked_names):
250 seen_vars = [ x[0] for x in asked_names ]
251 ctype = 'cnf'
252 if ')|' in text or '|(' in text:
253 ctype = 'dnf'
254
255 if ctype == 'cnf':
256 conds = text.split('&')
257 else:
258 conds = text.split('|')
259
[9371c30]260 for cond in conds:
261 if cond.startswith('(') and cond.endswith(')'):
262 cond = cond[1:-1]
[944b15c]263
264 inside = check_inside(cond, defaults, ctype, seen_vars)
265
266 if ctype == 'cnf' and not inside:
[9371c30]267 return False
[944b15c]268 if ctype == 'dnf' and inside:
269 return True
[9371c30]270
[944b15c]271 if ctype == 'cnf':
272 return True
273 return False
274
275def check_inside(text, defaults, ctype, seen_vars):
[9371c30]276 """
277 Check that the condition specified on input line is True
278
279 only CNF is supported
280 """
[944b15c]281 if ctype == 'cnf':
282 conds = text.split('|')
283 else:
284 conds = text.split('&')
[795ff98]285 for cond in conds:
[9371c30]286 res = re.match(r'^(.*?)(!?=)(.*)$', cond)
287 if not res:
288 raise RuntimeError("Invalid condition: %s" % cond)
289 condname = res.group(1)
290 oper = res.group(2)
291 condval = res.group(3)
[944b15c]292 if condname not in seen_vars:
[b4cad8b2]293 varval = ''
294## raise RuntimeError("Variable %s not defined before being asked." %\
295## condname)
296 elif not defaults.has_key(condname):
[795ff98]297 raise RuntimeError("Condition var %s does not exist: %s" % \
[9371c30]298 (condname,text))
[b4cad8b2]299 else:
300 varval = defaults[condname]
[944b15c]301 if ctype == 'cnf':
[b4cad8b2]302 if oper == '=' and condval == varval:
[944b15c]303 return True
[b4cad8b2]304 if oper == '!=' and condval != varval:
[944b15c]305 return True
306 else:
[b4cad8b2]307 if oper== '=' and condval != varval:
[944b15c]308 return False
[b4cad8b2]309 if oper== '!=' and condval == varval:
[944b15c]310 return False
311 if ctype=='cnf':
312 return False
313 return True
[34722ee]314
[beb39ee3]315def parse_config(input, output, dlg, defaults={}, askonly=None):
[090e7ea1]316 "Parse configuration file and create Makefile.config on the fly"
[9d5e23c]317 def ask_the_question(dialog):
[253f8590]318 "Ask question based on the type of variables to ask"
319 # This is quite a hack, this thingy is written just to
320 # have access to local variables..
321 if vartype == 'y/n':
[9d5e23c]322 return dialog.yesno(comment, default)
[253f8590]323 elif vartype == 'n/y':
[9d5e23c]324 return dialog.noyes(comment, default)
[253f8590]325 elif vartype == 'choice':
326 defopt = None
327 if default is not None:
328 for i,(key,val) in enumerate(choices):
329 if key == default:
330 defopt = i
331 break
[9d5e23c]332 return dialog.choice(comment, choices, defopt)
[253f8590]333 else:
334 raise RuntimeError("Bad method: %s" % vartype)
335
336
[34722ee]337 f = file(input, 'r')
338 outf = file(output, 'w')
339
340 outf.write('#########################################\n')
341 outf.write('## AUTO-GENERATED FILE, DO NOT EDIT!!! ##\n')
342 outf.write('#########################################\n\n')
343
[beb39ee3]344 asked_names = []
345
[34722ee]346 comment = ''
347 default = None
348 choices = []
[9371c30]349 for line in f:
350 if line.startswith('%'):
351 res = re.match(r'^%\s*(?:\[(.*?)\])?\s*(.*)$', line)
352 if not res:
353 raise RuntimeError('Invalid command: %s' % line)
354 if res.group(1):
[944b15c]355 if not check_condition(res.group(1), defaults,
356 asked_names):
[9371c30]357 continue
358 args = res.group(2).strip().split(' ')
359 cmd = args[0].lower()
360 args = args[1:]
[beb39ee3]361 if cmd == 'saveas':
[9371c30]362 outf.write('%s = %s\n' % (args[1],defaults[args[0]]))
[54257ba]363 elif cmd == 'shellcmd':
364 varname = args[0]
365 args = args[1:]
366 for i,arg in enumerate(args):
367 if arg.startswith('$'):
368 args[i] = defaults[arg[1:]]
[9d5e23c]369 data,status = commands.getstatusoutput(' '.join(args))
370 if status:
[54257ba]371 raise RuntimeError('Error running: %s' % ' '.join(args))
[9d5e23c]372 outf.write('%s = %s\n' % (varname,data.strip()))
[9371c30]373 continue
374
[34722ee]375 if line.startswith('!'):
[090e7ea1]376 # Ask a question
[795ff98]377 res = re.search(r'!\s*(?:\[(.*?)\])?\s*([^\s]+)\s*\((.*)\)\s*$', line)
[34722ee]378 if not res:
379 raise RuntimeError("Weird line: %s" % line)
[795ff98]380 varname = res.group(2)
381 vartype = res.group(3)
[34722ee]382
383 default = defaults.get(varname,None)
[beb39ee3]384
[795ff98]385 if res.group(1):
[944b15c]386 if not check_condition(res.group(1), defaults,
387 asked_names):
[795ff98]388 if default is not None:
389 outf.write('#!# %s = %s\n' % (varname, default))
[9371c30]390 # Clear cumulated values
391 comment = ''
392 default = None
393 choices = []
[795ff98]394 continue
[beb39ee3]395
396 asked_names.append((varname,comment))
397
[253f8590]398 if default is None or not askonly or askonly == varname:
[9d5e23c]399 default = ask_the_question(dlg)
400 else:
401 default = ask_the_question(DefaultDialog(dlg))
[795ff98]402
[253f8590]403 outf.write('%s = %s\n' % (varname, default))
[795ff98]404 # Remeber the selected value
[253f8590]405 defaults[varname] = default
[34722ee]406 # Clear cumulated values
407 comment = ''
408 default = None
409 choices = []
410 continue
411
412 if line.startswith('@'):
[090e7ea1]413 # Add new line into the 'choice array'
[795ff98]414 res = re.match(r'@\s*(?:\[(.*?)\])?\s*"(.*?)"\s*(.*)$', line)
[34722ee]415 if not res:
416 raise RuntimeError("Bad line: %s" % line)
[795ff98]417 if res.group(1):
[944b15c]418 if not check_condition(res.group(1),defaults,
419 asked_names):
[795ff98]420 continue
421 choices.append((res.group(2), res.group(3)))
[34722ee]422 continue
[090e7ea1]423
424 # All other things print to output file
[34722ee]425 outf.write(line)
426 if re.match(r'^#[^#]', line):
[090e7ea1]427 # Last comment before question will be displayed to the user
[34722ee]428 comment = line[1:].strip()
[2d93f1f9]429 elif line.startswith('## '):
[090e7ea1]430 # Set title of the dialog window
[34722ee]431 dlg.set_title(line[2:].strip())
[940cac0]432
433 outf.write('\n')
[13fded3]434 outf.write('REVISION = %s\n' % commands.getoutput('svnversion . 2> /dev/null'))
435 outf.write('TIMESTAMP = %s\n' % commands.getoutput('date "+%Y-%m-%d %H:%M:%S"'))
[34722ee]436 outf.close()
437 f.close()
[beb39ee3]438 return asked_names
[34722ee]439
440def main():
[9371c30]441 defaults = {}
[34722ee]442 try:
443 dlg = Dialog()
444 except NotImplementedError:
445 dlg = NoDialog()
446
[13fded3]447 if len(sys.argv) >= 2 and sys.argv[1]=='default':
[beb39ee3]448 defmode = True
449 else:
450 defmode = False
[34722ee]451
[beb39ee3]452 # Default run will update the configuration file
453 # with newest options
[34722ee]454 if os.path.exists(OUTPUT):
[795ff98]455 read_defaults(OUTPUT, defaults)
[994cf4b]456
[13fded3]457 # Get ARCH from command line if specified
458 if len(sys.argv) >= 3:
459 defaults['ARCH'] = sys.argv[2]
460
[994cf4b]461 # Dry run only with defaults
[beb39ee3]462 varnames = parse_config(INPUT, TMPOUTPUT, DefaultDialog(dlg), defaults)
463 # If not in default mode, present selection of all possibilities
464 if not defmode:
465 defopt = 0
466 while 1:
[994cf4b]467 # varnames contains variable names that were in the
468 # last question set
[beb39ee3]469 choices = [ (x[1],defaults[x[0]]) for x in varnames ]
470 res = dlg.menu('Configuration',choices,('save','Save'),defopt)
471 if res == 'save':
472 parse_config(INPUT, TMPOUTPUT, DefaultDialog(dlg), defaults)
473 break
474 # transfer description back to varname
475 for i,(vname,descr) in enumerate(varnames):
476 if res == descr:
477 defopt = i
478 break
[994cf4b]479 # Ask the user a simple question, produce output
480 # as if the user answered all the other questions
481 # with default answer
[beb39ee3]482 varnames = parse_config(INPUT, TMPOUTPUT, dlg, defaults,
483 askonly=varnames[i][0])
484
485
[34722ee]486 if os.path.exists(OUTPUT):
487 os.unlink(OUTPUT)
488 os.rename(TMPOUTPUT, OUTPUT)
[839470f]489
490 if not defmode and dlg.yesno('Rebuild kernel?') == 'y':
[944b15c]491 os.execlp('make','make','clean','build')
[34722ee]492
493if __name__ == '__main__':
494 main()
Note: See TracBrowser for help on using the repository browser.