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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 8b1e15ac was c01f8e6, checked in by Jiri Svoboda <jiri@…>, 15 years ago

Remove leftover code.

  • Property mode set to 100755
File size: 15.5 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 return False
88
89def check_inside(text, config, ctype):
90 "Check for condition"
91
92 if ctype == 'cnf':
93 conds = text.split('|')
94 else:
95 conds = text.split('&')
96
97 for cond in conds:
98 res = re.match(r'^(.*?)(!?=)(.*)$', cond)
99 if not res:
100 raise RuntimeError("Invalid condition: %s" % cond)
101
102 condname = res.group(1)
103 oper = res.group(2)
104 condval = res.group(3)
105
106 if not condname in config:
107 varval = ''
108 else:
109 varval = config[condname]
110 if (varval == '*'):
111 varval = 'y'
112
113 if ctype == 'cnf':
114 if (oper == '=') and (condval == varval):
115 return True
116
117 if (oper == '!=') and (condval != varval):
118 return True
119 else:
120 if (oper == '=') and (condval != varval):
121 return False
122
123 if (oper == '!=') and (condval == varval):
124 return False
125
126 if ctype == 'cnf':
127 return False
128
129 return True
130
131def parse_rules(fname, rules):
132 "Parse rules file"
133
134 inf = open(fname, 'r')
135
136 name = ''
137 choices = []
138
139 for line in inf:
140
141 if line.startswith('!'):
142 # Ask a question
143 res = re.search(r'!\s*(?:\[(.*?)\])?\s*([^\s]+)\s*\((.*)\)\s*$', line)
144
145 if not res:
146 raise RuntimeError("Weird line: %s" % line)
147
148 cond = res.group(1)
149 varname = res.group(2)
150 vartype = res.group(3)
151
152 rules.append((varname, vartype, name, choices, cond))
153 name = ''
154 choices = []
155 continue
156
157 if line.startswith('@'):
158 # Add new line into the 'choices' array
159 res = re.match(r'@\s*(?:\[(.*?)\])?\s*"(.*?)"\s*(.*)$', line)
160
161 if not res:
162 raise RuntimeError("Bad line: %s" % line)
163
164 choices.append((res.group(2), res.group(3)))
165 continue
166
167 if line.startswith('%'):
168 # Name of the option
169 name = line[1:].strip()
170 continue
171
172 if line.startswith('#') or (line == '\n'):
173 # Comment or empty line
174 continue
175
176
177 raise RuntimeError("Unknown syntax: %s" % line)
178
179 inf.close()
180
181def yes_no(default):
182 "Return '*' if yes, ' ' if no"
183
184 if default == 'y':
185 return '*'
186
187 return ' '
188
189def subchoice(screen, name, choices, default):
190 "Return choice of choices"
191
192 maxkey = 0
193 for key, val in choices:
194 length = len(key)
195 if (length > maxkey):
196 maxkey = length
197
198 options = []
199 position = None
200 cnt = 0
201 for key, val in choices:
202 if (default) and (key == default):
203 position = cnt
204
205 options.append(" %-*s %s " % (maxkey, key, val))
206 cnt += 1
207
208 (button, value) = xtui.choice_window(screen, name, 'Choose value', options, position)
209
210 if button == 'cancel':
211 return None
212
213 return choices[value][0]
214
215## Infer and verify configuration values.
216#
217# Augment @a config with values that can be inferred, purge invalid ones
218# and verify that all variables have a value (previously specified or inferred).
219#
220# @param config Configuration to work on
221# @param rules Rules
222#
223# @return True if configuration is complete and valid, False
224# otherwise.
225#
226def infer_verify_choices(config, rules):
227 "Infer and verify configuration values."
228
229 for rule in rules:
230 varname, vartype, name, choices, cond = rule
231
232 if cond and (not check_condition(cond, config, rules)):
233 continue
234
235 if not varname in config:
236 value = None
237 else:
238 value = config[varname]
239
240 if not validate_rule_value(rule, value):
241 value = None
242
243 default = get_default_rule(rule)
244
245 #
246 # If we don't have a value but we do have
247 # a default, use it.
248 #
249 if value == None and default != None:
250 value = default
251 config[varname] = default
252
253 if not varname in config:
254 return False
255
256 return True
257
258## Get default value from a rule.
259def get_default_rule(rule):
260 varname, vartype, name, choices, cond = rule
261
262 default = None
263
264 if vartype == 'choice':
265 # If there is just one option, use it
266 if len(choices) == 1:
267 default = choices[0][0]
268 elif vartype == 'y':
269 default = '*'
270 elif vartype == 'n':
271 default = 'n'
272 elif vartype == 'y/n':
273 default = 'y'
274 elif vartype == 'n/y':
275 default = 'n'
276 else:
277 raise RuntimeError("Unknown variable type: %s" % vartype)
278
279 return default
280
281## Get option from a rule.
282#
283# @param rule Rule for a variable
284# @param value Current value of the variable
285#
286# @return Option (string) to ask or None which means not to ask.
287#
288def get_rule_option(rule, value):
289 varname, vartype, name, choices, cond = rule
290
291 option = None
292
293 if vartype == 'choice':
294 # If there is just one option, don't ask
295 if len(choices) != 1:
296 if (value == None):
297 option = "? %s --> " % name
298 else:
299 option = " %s [%s] --> " % (name, value)
300 elif vartype == 'y':
301 pass
302 elif vartype == 'n':
303 pass
304 elif vartype == 'y/n':
305 option = " <%s> %s " % (yes_no(value), name)
306 elif vartype == 'n/y':
307 option =" <%s> %s " % (yes_no(value), name)
308 else:
309 raise RuntimeError("Unknown variable type: %s" % vartype)
310
311 return option
312
313## Check if variable value is valid.
314#
315# @param rule Rule for the variable
316# @param value Value of the variable
317#
318# @return True if valid, False if not valid.
319#
320def validate_rule_value(rule, value):
321 varname, vartype, name, choices, cond = rule
322
323 if value == None:
324 return True
325
326 if vartype == 'choice':
327 if not value in [choice[0] for choice in choices]:
328 return False
329 elif vartype == 'y':
330 if value != 'y':
331 return False
332 elif vartype == 'n':
333 if value != 'n':
334 return False
335 elif vartype == 'y/n':
336 if not value in ['y', 'n']:
337 return False
338 elif vartype == 'n/y':
339 if not value in ['y', 'n']:
340 return False
341 else:
342 raise RuntimeError("Unknown variable type: %s" % vartype)
343
344 return True
345
346def create_output(mkname, mcname, config, rules):
347 "Create output configuration"
348
349 timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
350
351 sys.stderr.write("Fetching current revision identifier ... ")
352
353 try:
354 version = subprocess.Popen(['bzr', 'version-info', '--custom', '--template={clean}:{revno}:{revision_id}'], stdout = subprocess.PIPE).communicate()[0].decode().split(':')
355 sys.stderr.write("ok\n")
356 except:
357 version = [1, "unknown", "unknown"]
358 sys.stderr.write("failed\n")
359
360 if len(version) == 3:
361 revision = version[1]
362 if version[0] != 1:
363 revision += 'M'
364 revision += ' (%s)' % version[2]
365 else:
366 revision = None
367
368 outmk = open(mkname, 'w')
369 outmc = open(mcname, 'w')
370
371 outmk.write('#########################################\n')
372 outmk.write('## AUTO-GENERATED FILE, DO NOT EDIT!!! ##\n')
373 outmk.write('#########################################\n\n')
374
375 outmc.write('/***************************************\n')
376 outmc.write(' * AUTO-GENERATED FILE, DO NOT EDIT!!! *\n')
377 outmc.write(' ***************************************/\n\n')
378
379 defs = 'CONFIG_DEFS ='
380
381 for varname, vartype, name, choices, cond in rules:
382 if cond and (not check_condition(cond, config, rules)):
383 continue
384
385 if not varname in config:
386 value = ''
387 else:
388 value = config[varname]
389 if (value == '*'):
390 value = 'y'
391
392 outmk.write('# %s\n%s = %s\n\n' % (name, varname, value))
393
394 if vartype in ["y", "n", "y/n", "n/y"]:
395 if value == "y":
396 outmc.write('/* %s */\n#define %s\n\n' % (name, varname))
397 defs += ' -D%s' % varname
398 else:
399 outmc.write('/* %s */\n#define %s %s\n#define %s_%s\n\n' % (name, varname, value, varname, value))
400 defs += ' -D%s=%s -D%s_%s' % (varname, value, varname, value)
401
402 if revision is not None:
403 outmk.write('REVISION = %s\n' % revision)
404 outmc.write('#define REVISION %s\n' % revision)
405 defs += ' "-DREVISION=%s"' % revision
406
407 outmk.write('TIMESTAMP = %s\n' % timestamp)
408 outmc.write('#define TIMESTAMP %s\n' % timestamp)
409 defs += ' "-DTIMESTAMP=%s"\n' % timestamp
410
411 outmk.write(defs)
412
413 outmk.close()
414 outmc.close()
415
416def sorted_dir(root):
417 list = os.listdir(root)
418 list.sort()
419 return list
420
421## Ask user to choose a configuration profile.
422#
423def choose_profile(root, fname, screen, config):
424 options = []
425 opt2path = {}
426 cnt = 0
427
428 # Look for profiles
429 for name in sorted_dir(root):
430 path = os.path.join(root, name)
431 canon = os.path.join(path, fname)
432
433 if os.path.isdir(path) and os.path.exists(canon) and os.path.isfile(canon):
434 subprofile = False
435
436 # Look for subprofiles
437 for subname in sorted_dir(path):
438 subpath = os.path.join(path, subname)
439 subcanon = os.path.join(subpath, fname)
440
441 if os.path.isdir(subpath) and os.path.exists(subcanon) and os.path.isfile(subcanon):
442 subprofile = True
443 options.append("%s (%s)" % (name, subname))
444 opt2path[cnt] = [name, subname]
445 cnt += 1
446
447 if not subprofile:
448 options.append(name)
449 opt2path[cnt] = [name]
450 cnt += 1
451
452 (button, value) = xtui.choice_window(screen, 'Load preconfigured defaults', 'Choose configuration profile', options, None)
453
454 if button == 'cancel':
455 return None
456
457 return opt2path[value]
458
459## Read presets from a configuration profile.
460#
461# @param profile Profile to load from (a list of string components)
462# @param config Output configuration
463#
464def read_presets(profile, config):
465 path = os.path.join(PRESETS_DIR, profile[0], MAKEFILE)
466 read_config(path, config)
467
468 if len(profile) > 1:
469 path = os.path.join(PRESETS_DIR, profile[0], profile[1], MAKEFILE)
470 read_config(path, config)
471
472## Parse profile name (relative OS path) into a list of components.
473#
474# @param profile_name Relative path (using OS separator)
475# @return List of components
476#
477def parse_profile_name(profile_name):
478 profile = []
479
480 head, tail = os.path.split(profile_name)
481 if head != '':
482 profile.append(head)
483
484 profile.append(tail)
485 return profile
486
487def main():
488 profile = None
489 config = {}
490 rules = []
491
492 # Parse rules file
493 parse_rules(RULES_FILE, rules)
494
495 # Input configuration file can be specified on command line
496 # otherwise configuration from previous run is used.
497 if len(sys.argv) >= 4:
498 profile = parse_profile_name(sys.argv[3])
499 read_presets(profile, config)
500 elif os.path.exists(MAKEFILE):
501 read_config(MAKEFILE, config)
502
503 # Default mode: check values and regenerate configuration files
504 if (len(sys.argv) >= 3) and (sys.argv[2] == 'default'):
505 if (infer_verify_choices(config, rules)):
506 create_output(MAKEFILE, MACROS, config, rules)
507 return 0
508
509 # Hands-off mode: check values and regenerate configuration files,
510 # but no interactive fallback
511 if (len(sys.argv) >= 3) and (sys.argv[2] == 'hands-off'):
512 # We deliberately test sys.argv >= 4 because we do not want
513 # to read implicitly any possible previous run configuration
514 if len(sys.argv) < 4:
515 sys.stderr.write("Configuration error: No presets specified\n")
516 return 2
517
518 if (infer_verify_choices(config, rules)):
519 create_output(MAKEFILE, MACROS, config, rules)
520 return 0
521
522 sys.stderr.write("Configuration error: The presets are ambiguous\n")
523 return 1
524
525 # Check mode: only check configuration
526 if (len(sys.argv) >= 3) and (sys.argv[2] == 'check'):
527 if infer_verify_choices(config, rules):
528 return 0
529 return 1
530
531 screen = xtui.screen_init()
532 try:
533 selname = None
534 position = None
535 while True:
536
537 # Cancel out all values which have to be deduced
538 for varname, vartype, name, choices, cond in rules:
539 if (vartype == 'y') and (varname in config) and (config[varname] == '*'):
540 config[varname] = None
541
542 options = []
543 opt2row = {}
544 cnt = 1
545
546 options.append(" --- Load preconfigured defaults ... ")
547
548 for rule in rules:
549 varname, vartype, name, choices, cond = rule
550
551 if cond and (not check_condition(cond, config, rules)):
552 continue
553
554 if varname == selname:
555 position = cnt
556
557 if not varname in config:
558 value = None
559 else:
560 value = config[varname]
561
562 if not validate_rule_value(rule, value):
563 value = None
564
565 default = get_default_rule(rule)
566
567 #
568 # If we don't have a value but we do have
569 # a default, use it.
570 #
571 if value == None and default != None:
572 value = default
573 config[varname] = default
574
575 option = get_rule_option(rule, value)
576 if option != None:
577 options.append(option)
578 else:
579 continue
580
581 opt2row[cnt] = (varname, vartype, name, choices)
582
583 cnt += 1
584
585 if (position != None) and (position >= len(options)):
586 position = None
587
588 (button, value) = xtui.choice_window(screen, 'HelenOS configuration', 'Choose configuration option', options, position)
589
590 if button == 'cancel':
591 return 'Configuration canceled'
592
593 if button == 'done':
594 if (infer_verify_choices(config, rules)):
595 break
596 else:
597 xtui.error_dialog(screen, 'Error', 'Some options have still undefined values. These options are marked with the "?" sign.')
598 continue
599
600 if value == 0:
601 profile = choose_profile(PRESETS_DIR, MAKEFILE, screen, config)
602 if profile != None:
603 read_presets(profile, config)
604 position = 1
605 continue
606
607 position = None
608 if not value in opt2row:
609 raise RuntimeError("Error selecting value: %s" % value)
610
611 (selname, seltype, name, choices) = opt2row[value]
612
613 if not selname in config:
614 value = None
615 else:
616 value = config[selname]
617
618 if seltype == 'choice':
619 config[selname] = subchoice(screen, name, choices, value)
620 elif (seltype == 'y/n') or (seltype == 'n/y'):
621 if config[selname] == 'y':
622 config[selname] = 'n'
623 else:
624 config[selname] = 'y'
625 finally:
626 xtui.screen_done(screen)
627
628 create_output(MAKEFILE, MACROS, config, rules)
629 return 0
630
631if __name__ == '__main__':
632 sys.exit(main())
Note: See TracBrowser for help on using the repository browser.