source: mainline/tools/config.py@ 8424198

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 8424198 was 13fded3, checked in by Martin Decky <martin@…>, 19 years ago

allow setting ARCH from Makefile argument

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