source: mainline/tools/config.py@ 090e7ea1

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

Doc cleanup.

  • Property mode set to 100755
File size: 9.1 KB
Line 
1#!/usr/bin/env python
2"""
3Kernel configuration script
4"""
5import sys
6import os
7import re
8
9INPUT = 'kernel.config'
10OUTPUT = 'Makefile.config'
11TMPOUTPUT = 'Makefile.config.tmp'
12
13class 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
35class 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:
42 sys.stdout.write("*** %s ***\n" % self.title)
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: ')
80
81 def choice(self, text, choices, defopt=None):
82 self.print_title()
83 while 1:
84 self._print_choice(text, choices, defopt)
85 inp = sys.stdin.readline()
86 if not inp:
87 raise EOFError
88 if not inp.strip():
89 if defopt is not None:
90 return choices[defopt][0]
91 continue
92 try:
93 number = int(inp.strip())
94 except ValueError:
95 continue
96 if number < 0 or number >= len(choices):
97 continue
98 return choices[number][0]
99
100
101class Dialog(NoDialog):
102 def __init__(self):
103 NoDialog.__init__(self)
104 self.dlgcmd = os.environ.get('DIALOG','dialog')
105 self.title = 'HelenOS Configuration'
106
107 if os.system('%s --print-maxsize >/dev/null 2>&1' % self.dlgcmd) != 0:
108 raise NotImplementedError
109
110 def set_title(self,text):
111 self.title = text
112
113 def calldlg(self,*args,**kw):
114 "Wrapper for calling 'dialog' program"
115 indesc, outdesc = os.pipe()
116 pid = os.fork()
117 if not pid:
118 os.close(2)
119 os.dup(outdesc)
120 os.close(indesc)
121
122 dlgargs = [self.dlgcmd,'--title',self.title]
123 for key,val in kw.items():
124 dlgargs.append('--'+key)
125 dlgargs.append(val)
126 dlgargs += args
127 os.execlp(self.dlgcmd,*dlgargs)
128
129 os.close(outdesc)
130 errout = os.fdopen(indesc,'r')
131 data = errout.read()
132 errout.close()
133
134 pid,status = os.wait()
135 if not os.WIFEXITED(status):
136 raise EOFError
137 status = os.WEXITSTATUS(status)
138 if status == 255:
139 raise EOFError
140 return status,data
141
142 def yesno(self, text, default=None):
143 text = text + ':'
144 width = '50'
145 height = '5'
146 if len(text) < 48:
147 text = ' '*int(((48-len(text))/2)) + text
148 else:
149 width = '0'
150 height = '0'
151 if default == 'n':
152 res,data = self.calldlg('--defaultno','--yesno',text,height,width)
153 else:
154 res,data = self.calldlg('--yesno',text,height,width)
155
156 if res == 0:
157 return 'y'
158 return 'n'
159
160 def choice(self, text, choices, defopt=None):
161 text = text + ':'
162 width = '50'
163 height = str(8 + len(choices))
164 args = []
165 for key,val in choices:
166 args.append(key)
167 args.append(val)
168
169 kw = {}
170 if defopt:
171 kw['default-item'] = choices[defopt][0]
172 res,data = self.calldlg('--nocancel','--menu',text,height,width,
173 str(len(choices)),*args, **kw)
174 if res:
175 print data
176 raise EOFError
177 return data
178
179def read_defaults(fname,defaults):
180 "Read saved values from last configuration run"
181 f = file(fname,'r')
182 for line in f:
183 res = re.match(r'^(?:#!# )?([^#]\w*)\s*=\s*(.*?)\s*$', line)
184 if res:
185 defaults[res.group(1)] = res.group(2)
186 f.close()
187
188def check_condition(text, defaults):
189 "Check that the condition specified on input line is True"
190 result = False
191 conds = text.split('|')
192 for cond in conds:
193 condname,condval = cond.split('=')
194 if not defaults.has_key(condname):
195 raise RuntimeError("Condition var %s does not exist: %s" % \
196 (condname,line))
197 # None means wildcard
198 if defaults[condname] is None:
199 return True
200 if condval == defaults[condname]:
201 return True
202 return False
203
204def parse_config(input, output, dlg, defaults={}):
205 "Parse configuration file and create Makefile.config on the fly"
206 f = file(input, 'r')
207 outf = file(output, 'w')
208
209 outf.write('#########################################\n')
210 outf.write('## AUTO-GENERATED FILE, DO NOT EDIT!!! ##\n')
211 outf.write('#########################################\n\n')
212
213 comment = ''
214 default = None
215 choices = []
216 for line in f:
217 if line.startswith('!'):
218 # Ask a question
219 res = re.search(r'!\s*(?:\[(.*?)\])?\s*([^\s]+)\s*\((.*)\)\s*$', line)
220 if not res:
221 raise RuntimeError("Weird line: %s" % line)
222 varname = res.group(2)
223 vartype = res.group(3)
224
225 default = defaults.get(varname,None)
226
227 if res.group(1):
228 if not check_condition(res.group(1), defaults):
229 if default is not None:
230 outf.write('#!# %s = %s\n' % (varname, default))
231 continue
232
233 if vartype == 'y/n':
234 result = dlg.yesno(comment, default)
235 elif vartype == 'n/y':
236 result = dlg.noyes(comment, default)
237 elif vartype == 'choice':
238 defopt = None
239 if default is not None:
240 for i,(key,val) in enumerate(choices):
241 if key == default:
242 defopt = i
243 break
244 result = dlg.choice(comment, choices, defopt)
245 else:
246 raise RuntimeError("Bad method: %s" % vartype)
247 outf.write('%s = %s\n' % (varname, result))
248 # Remeber the selected value
249 defaults[varname] = result
250 # Clear cumulated values
251 comment = ''
252 default = None
253 choices = []
254 continue
255
256 if line.startswith('@'):
257 # Add new line into the 'choice array'
258 res = re.match(r'@\s*(?:\[(.*?)\])?\s*"(.*?)"\s*(.*)$', line)
259 if not res:
260 raise RuntimeError("Bad line: %s" % line)
261 if res.group(1):
262 if not check_condition(res.group(1),defaults):
263 continue
264 choices.append((res.group(2), res.group(3)))
265 continue
266
267 # All other things print to output file
268 outf.write(line)
269 if re.match(r'^#[^#]', line):
270 # Last comment before question will be displayed to the user
271 comment = line[1:].strip()
272 elif line.startswith('##'):
273 # Set title of the dialog window
274 dlg.set_title(line[2:].strip())
275
276 outf.close()
277 f.close()
278
279def main():
280 defaults = {'ARCH':None}
281 try:
282 dlg = Dialog()
283 except NotImplementedError:
284 dlg = NoDialog()
285
286 # Default run will update the configuration file
287 # with newest options
288 if len(sys.argv) >= 2:
289 defaults['ARCH'] = sys.argv[1]
290 if len(sys.argv) == 3 and sys.argv[2]=='default':
291 dlg = DefaultDialog(dlg)
292
293 if os.path.exists(OUTPUT):
294 read_defaults(OUTPUT, defaults)
295
296 parse_config(INPUT, TMPOUTPUT, dlg, defaults)
297 if os.path.exists(OUTPUT):
298 os.unlink(OUTPUT)
299 os.rename(TMPOUTPUT, OUTPUT)
300
301
302if __name__ == '__main__':
303 main()
Note: See TracBrowser for help on using the repository browser.