source: mainline/tools/config.py@ beb9336

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

implement multiboot v2 specification and use it in GRUB for UEFI

  • improve multiboot v1 code, move defines to a common location
  • rename VESA framebuffer stuff to generic "boot framebuffer"
  • small collateral changes
  • Property mode set to 100755
File size: 16.1 KB
Line 
1#!/usr/bin/env python
2#
3# Copyright (c) 2006 Ondrej Palkovsky
4# Copyright (c) 2009 Martin Decky
5# Copyright (c) 2010 Jiri Svoboda
6# All rights reserved.
7#
8# Redistribution and use in source and binary forms, with or without
9# modification, are permitted provided that the following conditions
10# are met:
11#
12# - Redistributions of source code must retain the above copyright
13# notice, this list of conditions and the following disclaimer.
14# - Redistributions in binary form must reproduce the above copyright
15# notice, this list of conditions and the following disclaimer in the
16# documentation and/or other materials provided with the distribution.
17# - The name of the author may not be used to endorse or promote products
18# derived from this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30#
31
32"""
33HelenOS configuration system
34"""
35
36import sys
37import os
38import re
39import time
40import subprocess
41import xtui
42
43RULES_FILE = sys.argv[1]
44MAKEFILE = 'Makefile.config'
45MACROS = 'config.h'
46PRESETS_DIR = 'defaults'
47
48def read_config(fname, config):
49 "Read saved values from last configuration run or a preset file"
50
51 inf = open(fname, 'r')
52
53 for line in inf:
54 res = re.match(r'^(?:#!# )?([^#]\w*)\s*=\s*(.*?)\s*$', line)
55 if res:
56 config[res.group(1)] = res.group(2)
57
58 inf.close()
59
60def check_condition(text, config, rules):
61 "Check that the condition specified on input line is True (only CNF and DNF is supported)"
62
63 ctype = 'cnf'
64
65 if (')|' in text) or ('|(' in text):
66 ctype = 'dnf'
67
68 if ctype == 'cnf':
69 conds = text.split('&')
70 else:
71 conds = text.split('|')
72
73 for cond in conds:
74 if cond.startswith('(') and cond.endswith(')'):
75 cond = cond[1:-1]
76
77 inside = check_inside(cond, config, ctype)
78
79 if (ctype == 'cnf') and (not inside):
80 return False
81
82 if (ctype == 'dnf') and inside:
83 return True
84
85 if ctype == 'cnf':
86 return True
87
88 return False
89
90def check_inside(text, config, ctype):
91 "Check for condition"
92
93 if ctype == 'cnf':
94 conds = text.split('|')
95 else:
96 conds = text.split('&')
97
98 for cond in conds:
99 res = re.match(r'^(.*?)(!?=)(.*)$', cond)
100 if not res:
101 raise RuntimeError("Invalid condition: %s" % cond)
102
103 condname = res.group(1)
104 oper = res.group(2)
105 condval = res.group(3)
106
107 if not condname in config:
108 varval = ''
109 else:
110 varval = config[condname]
111 if (varval == '*'):
112 varval = 'y'
113
114 if ctype == 'cnf':
115 if (oper == '=') and (condval == varval):
116 return True
117
118 if (oper == '!=') and (condval != varval):
119 return True
120 else:
121 if (oper == '=') and (condval != varval):
122 return False
123
124 if (oper == '!=') and (condval == varval):
125 return False
126
127 if ctype == 'cnf':
128 return False
129
130 return True
131
132def parse_rules(fname, rules):
133 "Parse rules file"
134
135 inf = open(fname, 'r')
136
137 name = ''
138 choices = []
139
140 for line in inf:
141
142 if line.startswith('!'):
143 # Ask a question
144 res = re.search(r'!\s*(?:\[(.*?)\])?\s*([^\s]+)\s*\((.*)\)\s*$', line)
145
146 if not res:
147 raise RuntimeError("Weird line: %s" % line)
148
149 cond = res.group(1)
150 varname = res.group(2)
151 vartype = res.group(3)
152
153 rules.append((varname, vartype, name, choices, cond))
154 name = ''
155 choices = []
156 continue
157
158 if line.startswith('@'):
159 # Add new line into the 'choices' array
160 res = re.match(r'@\s*(?:\[(.*?)\])?\s*"(.*?)"\s*(.*)$', line)
161
162 if not res:
163 raise RuntimeError("Bad line: %s" % line)
164
165 choices.append((res.group(2), res.group(3)))
166 continue
167
168 if line.startswith('%'):
169 # Name of the option
170 name = line[1:].strip()
171 continue
172
173 if line.startswith('#') or (line == '\n'):
174 # Comment or empty line
175 continue
176
177
178 raise RuntimeError("Unknown syntax: %s" % line)
179
180 inf.close()
181
182def yes_no(default):
183 "Return '*' if yes, ' ' if no"
184
185 if default == 'y':
186 return '*'
187
188 return ' '
189
190def subchoice(screen, name, choices, default):
191 "Return choice of choices"
192
193 maxkey = 0
194 for key, val in choices:
195 length = len(key)
196 if (length > maxkey):
197 maxkey = length
198
199 options = []
200 position = None
201 cnt = 0
202 for key, val in choices:
203 if (default) and (key == default):
204 position = cnt
205
206 options.append(" %-*s %s " % (maxkey, key, val))
207 cnt += 1
208
209 (button, value) = xtui.choice_window(screen, name, 'Choose value', options, position)
210
211 if button == 'cancel':
212 return None
213
214 return choices[value][0]
215
216## Infer and verify configuration values.
217#
218# Augment @a config with values that can be inferred, purge invalid ones
219# and verify that all variables have a value (previously specified or inferred).
220#
221# @param config Configuration to work on
222# @param rules Rules
223#
224# @return True if configuration is complete and valid, False
225# otherwise.
226#
227def infer_verify_choices(config, rules):
228 "Infer and verify configuration values."
229
230 for rule in rules:
231 varname, vartype, name, choices, cond = rule
232
233 if cond and (not check_condition(cond, config, rules)):
234 continue
235
236 if not varname in config:
237 value = None
238 else:
239 value = config[varname]
240
241 if not validate_rule_value(rule, value):
242 value = None
243
244 default = get_default_rule(rule)
245
246 #
247 # If we don't have a value but we do have
248 # a default, use it.
249 #
250 if value == None and default != None:
251 value = default
252 config[varname] = default
253
254 if not varname in config:
255 return False
256
257 return True
258
259## Get default value from a rule.
260def get_default_rule(rule):
261 varname, vartype, name, choices, cond = rule
262
263 default = None
264
265 if vartype == 'choice':
266 # If there is just one option, use it
267 if len(choices) == 1:
268 default = choices[0][0]
269 elif vartype == 'y':
270 default = '*'
271 elif vartype == 'n':
272 default = 'n'
273 elif vartype == 'y/n':
274 default = 'y'
275 elif vartype == 'n/y':
276 default = 'n'
277 else:
278 raise RuntimeError("Unknown variable type: %s" % vartype)
279
280 return default
281
282## Get option from a rule.
283#
284# @param rule Rule for a variable
285# @param value Current value of the variable
286#
287# @return Option (string) to ask or None which means not to ask.
288#
289def get_rule_option(rule, value):
290 varname, vartype, name, choices, cond = rule
291
292 option = None
293
294 if vartype == 'choice':
295 # If there is just one option, don't ask
296 if len(choices) != 1:
297 if (value == None):
298 option = "? %s --> " % name
299 else:
300 option = " %s [%s] --> " % (name, value)
301 elif vartype == 'y':
302 pass
303 elif vartype == 'n':
304 pass
305 elif vartype == 'y/n':
306 option = " <%s> %s " % (yes_no(value), name)
307 elif vartype == 'n/y':
308 option =" <%s> %s " % (yes_no(value), name)
309 else:
310 raise RuntimeError("Unknown variable type: %s" % vartype)
311
312 return option
313
314## Check if variable value is valid.
315#
316# @param rule Rule for the variable
317# @param value Value of the variable
318#
319# @return True if valid, False if not valid.
320#
321def validate_rule_value(rule, value):
322 varname, vartype, name, choices, cond = rule
323
324 if value == None:
325 return True
326
327 if vartype == 'choice':
328 if not value in [choice[0] for choice in choices]:
329 return False
330 elif vartype == 'y':
331 if value != 'y':
332 return False
333 elif vartype == 'n':
334 if value != 'n':
335 return False
336 elif vartype == 'y/n':
337 if not value in ['y', 'n']:
338 return False
339 elif vartype == 'n/y':
340 if not value in ['y', 'n']:
341 return False
342 else:
343 raise RuntimeError("Unknown variable type: %s" % vartype)
344
345 return True
346
347def preprocess_config(config, rules):
348 "Preprocess configuration"
349
350 varname_mode = 'CONFIG_BFB_MODE'
351 varname_width = 'CONFIG_BFB_WIDTH'
352 varname_height = 'CONFIG_BFB_HEIGHT'
353
354 if varname_mode in config:
355 mode = config[varname_mode].partition('x')
356
357 config[varname_width] = mode[0]
358 rules.append((varname_width, 'choice', 'Default framebuffer width', None, None))
359
360 config[varname_height] = mode[2]
361 rules.append((varname_height, 'choice', 'Default framebuffer height', None, None))
362
363def create_output(mkname, mcname, config, rules):
364 "Create output configuration"
365
366 timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
367
368 sys.stderr.write("Fetching current revision identifier ... ")
369
370 try:
371 version = subprocess.Popen(['bzr', 'version-info', '--custom', '--template={clean}:{revno}:{revision_id}'], stdout = subprocess.PIPE).communicate()[0].decode().split(':')
372 sys.stderr.write("ok\n")
373 except:
374 version = [1, "unknown", "unknown"]
375 sys.stderr.write("failed\n")
376
377 if len(version) == 3:
378 revision = version[1]
379 if version[0] != 1:
380 revision += 'M'
381 revision += ' (%s)' % version[2]
382 else:
383 revision = None
384
385 outmk = open(mkname, 'w')
386 outmc = open(mcname, 'w')
387
388 outmk.write('#########################################\n')
389 outmk.write('## AUTO-GENERATED FILE, DO NOT EDIT!!! ##\n')
390 outmk.write('#########################################\n\n')
391
392 outmc.write('/***************************************\n')
393 outmc.write(' * AUTO-GENERATED FILE, DO NOT EDIT!!! *\n')
394 outmc.write(' ***************************************/\n\n')
395
396 defs = 'CONFIG_DEFS ='
397
398 for varname, vartype, name, choices, cond in rules:
399 if cond and (not check_condition(cond, config, rules)):
400 continue
401
402 if not varname in config:
403 value = ''
404 else:
405 value = config[varname]
406 if (value == '*'):
407 value = 'y'
408
409 outmk.write('# %s\n%s = %s\n\n' % (name, varname, value))
410
411 if vartype in ["y", "n", "y/n", "n/y"]:
412 if value == "y":
413 outmc.write('/* %s */\n#define %s\n\n' % (name, varname))
414 defs += ' -D%s' % varname
415 else:
416 outmc.write('/* %s */\n#define %s %s\n#define %s_%s\n\n' % (name, varname, value, varname, value))
417 defs += ' -D%s=%s -D%s_%s' % (varname, value, varname, value)
418
419 if revision is not None:
420 outmk.write('REVISION = %s\n' % revision)
421 outmc.write('#define REVISION %s\n' % revision)
422 defs += ' "-DREVISION=%s"' % revision
423
424 outmk.write('TIMESTAMP = %s\n' % timestamp)
425 outmc.write('#define TIMESTAMP %s\n' % timestamp)
426 defs += ' "-DTIMESTAMP=%s"\n' % timestamp
427
428 outmk.write(defs)
429
430 outmk.close()
431 outmc.close()
432
433def sorted_dir(root):
434 list = os.listdir(root)
435 list.sort()
436 return list
437
438## Ask user to choose a configuration profile.
439#
440def choose_profile(root, fname, screen, config):
441 options = []
442 opt2path = {}
443 cnt = 0
444
445 # Look for profiles
446 for name in sorted_dir(root):
447 path = os.path.join(root, name)
448 canon = os.path.join(path, fname)
449
450 if os.path.isdir(path) and os.path.exists(canon) and os.path.isfile(canon):
451 subprofile = False
452
453 # Look for subprofiles
454 for subname in sorted_dir(path):
455 subpath = os.path.join(path, subname)
456 subcanon = os.path.join(subpath, fname)
457
458 if os.path.isdir(subpath) and os.path.exists(subcanon) and os.path.isfile(subcanon):
459 subprofile = True
460 options.append("%s (%s)" % (name, subname))
461 opt2path[cnt] = [name, subname]
462 cnt += 1
463
464 if not subprofile:
465 options.append(name)
466 opt2path[cnt] = [name]
467 cnt += 1
468
469 (button, value) = xtui.choice_window(screen, 'Load preconfigured defaults', 'Choose configuration profile', options, None)
470
471 if button == 'cancel':
472 return None
473
474 return opt2path[value]
475
476## Read presets from a configuration profile.
477#
478# @param profile Profile to load from (a list of string components)
479# @param config Output configuration
480#
481def read_presets(profile, config):
482 path = os.path.join(PRESETS_DIR, profile[0], MAKEFILE)
483 read_config(path, config)
484
485 if len(profile) > 1:
486 path = os.path.join(PRESETS_DIR, profile[0], profile[1], MAKEFILE)
487 read_config(path, config)
488
489## Parse profile name (relative OS path) into a list of components.
490#
491# @param profile_name Relative path (using OS separator)
492# @return List of components
493#
494def parse_profile_name(profile_name):
495 profile = []
496
497 head, tail = os.path.split(profile_name)
498 if head != '':
499 profile.append(head)
500
501 profile.append(tail)
502 return profile
503
504def main():
505 profile = None
506 config = {}
507 rules = []
508
509 # Parse rules file
510 parse_rules(RULES_FILE, rules)
511
512 # Input configuration file can be specified on command line
513 # otherwise configuration from previous run is used.
514 if len(sys.argv) >= 4:
515 profile = parse_profile_name(sys.argv[3])
516 read_presets(profile, config)
517 elif os.path.exists(MAKEFILE):
518 read_config(MAKEFILE, config)
519
520 # Default mode: check values and regenerate configuration files
521 if (len(sys.argv) >= 3) and (sys.argv[2] == 'default'):
522 if (infer_verify_choices(config, rules)):
523 preprocess_config(config, rules)
524 create_output(MAKEFILE, MACROS, config, rules)
525 return 0
526
527 # Hands-off mode: check values and regenerate configuration files,
528 # but no interactive fallback
529 if (len(sys.argv) >= 3) and (sys.argv[2] == 'hands-off'):
530 # We deliberately test sys.argv >= 4 because we do not want
531 # to read implicitly any possible previous run configuration
532 if len(sys.argv) < 4:
533 sys.stderr.write("Configuration error: No presets specified\n")
534 return 2
535
536 if (infer_verify_choices(config, rules)):
537 preprocess_config(config, rules)
538 create_output(MAKEFILE, MACROS, config, rules)
539 return 0
540
541 sys.stderr.write("Configuration error: The presets are ambiguous\n")
542 return 1
543
544 # Check mode: only check configuration
545 if (len(sys.argv) >= 3) and (sys.argv[2] == 'check'):
546 if infer_verify_choices(config, rules):
547 return 0
548 return 1
549
550 screen = xtui.screen_init()
551 try:
552 selname = None
553 position = None
554 while True:
555
556 # Cancel out all values which have to be deduced
557 for varname, vartype, name, choices, cond in rules:
558 if (vartype == 'y') and (varname in config) and (config[varname] == '*'):
559 config[varname] = None
560
561 options = []
562 opt2row = {}
563 cnt = 1
564
565 options.append(" --- Load preconfigured defaults ... ")
566
567 for rule in rules:
568 varname, vartype, name, choices, cond = rule
569
570 if cond and (not check_condition(cond, config, rules)):
571 continue
572
573 if varname == selname:
574 position = cnt
575
576 if not varname in config:
577 value = None
578 else:
579 value = config[varname]
580
581 if not validate_rule_value(rule, value):
582 value = None
583
584 default = get_default_rule(rule)
585
586 #
587 # If we don't have a value but we do have
588 # a default, use it.
589 #
590 if value == None and default != None:
591 value = default
592 config[varname] = default
593
594 option = get_rule_option(rule, value)
595 if option != None:
596 options.append(option)
597 else:
598 continue
599
600 opt2row[cnt] = (varname, vartype, name, choices)
601
602 cnt += 1
603
604 if (position != None) and (position >= len(options)):
605 position = None
606
607 (button, value) = xtui.choice_window(screen, 'HelenOS configuration', 'Choose configuration option', options, position)
608
609 if button == 'cancel':
610 return 'Configuration canceled'
611
612 if button == 'done':
613 if (infer_verify_choices(config, rules)):
614 break
615 else:
616 xtui.error_dialog(screen, 'Error', 'Some options have still undefined values. These options are marked with the "?" sign.')
617 continue
618
619 if value == 0:
620 profile = choose_profile(PRESETS_DIR, MAKEFILE, screen, config)
621 if profile != None:
622 read_presets(profile, config)
623 position = 1
624 continue
625
626 position = None
627 if not value in opt2row:
628 raise RuntimeError("Error selecting value: %s" % value)
629
630 (selname, seltype, name, choices) = opt2row[value]
631
632 if not selname in config:
633 value = None
634 else:
635 value = config[selname]
636
637 if seltype == 'choice':
638 config[selname] = subchoice(screen, name, choices, value)
639 elif (seltype == 'y/n') or (seltype == 'n/y'):
640 if config[selname] == 'y':
641 config[selname] = 'n'
642 else:
643 config[selname] = 'y'
644 finally:
645 xtui.screen_done(screen)
646
647 preprocess_config(config, rules)
648 create_output(MAKEFILE, MACROS, config, rules)
649 return 0
650
651if __name__ == '__main__':
652 sys.exit(main())
Note: See TracBrowser for help on using the repository browser.