~martin-decky/helenos/rcu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
#!/usr/bin/env python
#
# Copyright (c) 2006 Ondrej Palkovsky
# Copyright (c) 2009 Martin Decky
# Copyright (c) 2010 Jiri Svoboda
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# - The name of the author may not be used to endorse or promote products
#   derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

"""
HelenOS configuration system
"""

import sys
import os
import re
import time
import subprocess
import xtui

RULES_FILE = sys.argv[1]
MAKEFILE = 'Makefile.config'
MACROS = 'config.h'
PRESETS_DIR = 'defaults'

def read_config(fname, config):
	"Read saved values from last configuration run or a preset file"
	
	inf = open(fname, 'r')
	
	for line in inf:
		res = re.match(r'^(?:#!# )?([^#]\w*)\s*=\s*(.*?)\s*$', line)
		if res:
			config[res.group(1)] = res.group(2)
	
	inf.close()

def check_condition(text, config, rules):
	"Check that the condition specified on input line is True (only CNF and DNF is supported)"
	
	ctype = 'cnf'
	
	if (')|' in text) or ('|(' in text):
		ctype = 'dnf'
	
	if ctype == 'cnf':
		conds = text.split('&')
	else:
		conds = text.split('|')
	
	for cond in conds:
		if cond.startswith('(') and cond.endswith(')'):
			cond = cond[1:-1]
		
		inside = check_inside(cond, config, ctype)
		
		if (ctype == 'cnf') and (not inside):
			return False
		
		if (ctype == 'dnf') and inside:
			return True
	
	if ctype == 'cnf':
		return True
	
	return False

def check_inside(text, config, ctype):
	"Check for condition"
	
	if ctype == 'cnf':
		conds = text.split('|')
	else:
		conds = text.split('&')
	
	for cond in conds:
		res = re.match(r'^(.*?)(!?=)(.*)$', cond)
		if not res:
			raise RuntimeError("Invalid condition: %s" % cond)
		
		condname = res.group(1)
		oper = res.group(2)
		condval = res.group(3)
		
		if not condname in config:
			varval = ''
		else:
			varval = config[condname]
			if (varval == '*'):
				varval = 'y'
		
		if ctype == 'cnf':
			if (oper == '=') and (condval == varval):
				return True
		
			if (oper == '!=') and (condval != varval):
				return True
		else:
			if (oper == '=') and (condval != varval):
				return False
			
			if (oper == '!=') and (condval == varval):
				return False
	
	if ctype == 'cnf':
		return False
	
	return True

def parse_rules(fname, rules):
	"Parse rules file"
	
	inf = open(fname, 'r')
	
	name = ''
	choices = []
	
	for line in inf:
		
		if line.startswith('!'):
			# Ask a question
			res = re.search(r'!\s*(?:\[(.*?)\])?\s*([^\s]+)\s*\((.*)\)\s*$', line)
			
			if not res:
				raise RuntimeError("Weird line: %s" % line)
			
			cond = res.group(1)
			varname = res.group(2)
			vartype = res.group(3)
			
			rules.append((varname, vartype, name, choices, cond))
			name = ''
			choices = []
			continue
		
		if line.startswith('@'):
			# Add new line into the 'choices' array
			res = re.match(r'@\s*(?:\[(.*?)\])?\s*"(.*?)"\s*(.*)$', line)
			
			if not res:
				raise RuntimeError("Bad line: %s" % line)
			
			choices.append((res.group(2), res.group(3)))
			continue
		
		if line.startswith('%'):
			# Name of the option
			name = line[1:].strip()
			continue
		
		if line.startswith('#') or (line == '\n'):
			# Comment or empty line
			continue
		
		
		raise RuntimeError("Unknown syntax: %s" % line)
	
	inf.close()

def yes_no(default):
	"Return '*' if yes, ' ' if no"
	
	if default == 'y':
		return '*'
	
	return ' '

def subchoice(screen, name, choices, default):
	"Return choice of choices"
	
	maxkey = 0
	for key, val in choices:
		length = len(key)
		if (length > maxkey):
			maxkey = length
	
	options = []
	position = None
	cnt = 0
	for key, val in choices:
		if (default) and (key == default):
			position = cnt
		
		options.append(" %-*s  %s " % (maxkey, key, val))
		cnt += 1
	
	(button, value) = xtui.choice_window(screen, name, 'Choose value', options, position)
	
	if button == 'cancel':
		return None
	
	return choices[value][0]

## Infer and verify configuration values.
#
# Augment @a config with values that can be inferred, purge invalid ones
# and verify that all variables have a value (previously specified or inferred).
#
# @param config Configuration to work on
# @param rules  Rules
#
# @return True if configuration is complete and valid, False
#         otherwise.
#
def infer_verify_choices(config, rules):
	"Infer and verify configuration values."
	
	for rule in rules:
		varname, vartype, name, choices, cond = rule
		
		if cond and (not check_condition(cond, config, rules)):
			continue
		
		if not varname in config:
			value = None
		else:
			value = config[varname]
		
		if not validate_rule_value(rule, value):
			value = None
		
		default = get_default_rule(rule)
		
		#
		# If we don't have a value but we do have
		# a default, use it.
		#
		if value == None and default != None:
			value = default
			config[varname] = default
		
		if not varname in config:
			return False
	
	return True

## Get default value from a rule.
def get_default_rule(rule):
	varname, vartype, name, choices, cond = rule
	
	default = None
	
	if vartype == 'choice':
		# If there is just one option, use it
		if len(choices) == 1:
			default = choices[0][0]
	elif vartype == 'y':
		default = '*'
	elif vartype == 'n':
		default = 'n'
	elif vartype == 'y/n':
		default = 'y'
	elif vartype == 'n/y':
		default = 'n'
	else:
		raise RuntimeError("Unknown variable type: %s" % vartype)
	
	return default

## Get option from a rule.
#
# @param rule  Rule for a variable
# @param value Current value of the variable
#
# @return Option (string) to ask or None which means not to ask.
#
def get_rule_option(rule, value):
	varname, vartype, name, choices, cond = rule
	
	option = None
	
	if vartype == 'choice':
		# If there is just one option, don't ask
		if len(choices) != 1:
			if (value == None):
				option = "?     %s --> " % name
			else:
				option = "      %s [%s] --> " % (name, value)
	elif vartype == 'y':
		pass
	elif vartype == 'n':
		pass
	elif vartype == 'y/n':
		option = "  <%s> %s " % (yes_no(value), name)
	elif vartype == 'n/y':
		option ="  <%s> %s " % (yes_no(value), name)
	else:
		raise RuntimeError("Unknown variable type: %s" % vartype)
	
	return option

## Check if variable value is valid.
#
# @param rule  Rule for the variable
# @param value Value of the variable
#
# @return True if valid, False if not valid.
#
def validate_rule_value(rule, value):
	varname, vartype, name, choices, cond = rule
	
	if value == None:
		return True
	
	if vartype == 'choice':
		if not value in [choice[0] for choice in choices]:
			return False
	elif vartype == 'y':
		if value != 'y':
			return False
	elif vartype == 'n':
		if value != 'n':
			return False
	elif vartype == 'y/n':
		if not value in ['y', 'n']:
			return False
	elif vartype == 'n/y':
		if not value in ['y', 'n']:
			return False
	else:
		raise RuntimeError("Unknown variable type: %s" % vartype)
	
	return True

def preprocess_config(config, rules):
	"Preprocess configuration"
	
	varname_mode = 'CONFIG_BFB_MODE'
	varname_width = 'CONFIG_BFB_WIDTH'
	varname_height = 'CONFIG_BFB_HEIGHT'
	
	if varname_mode in config:
		mode = config[varname_mode].partition('x')
		
		config[varname_width] = mode[0]
		rules.append((varname_width, 'choice', 'Default framebuffer width', None, None))
		
		config[varname_height] = mode[2]
		rules.append((varname_height, 'choice', 'Default framebuffer height', None, None))

def create_output(mkname, mcname, config, rules):
	"Create output configuration"
	
	timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
	
	sys.stderr.write("Fetching current revision identifier ... ")
	
	try:
		version = subprocess.Popen(['bzr', 'version-info', '--custom', '--template={clean}:{revno}:{revision_id}'], stdout = subprocess.PIPE).communicate()[0].decode().split(':')
		sys.stderr.write("ok\n")
	except:
		version = [1, "unknown", "unknown"]
		sys.stderr.write("failed\n")
	
	if len(version) == 3:
		revision = version[1]
		if version[0] != 1:
			revision += 'M'
		revision += ' (%s)' % version[2]
	else:
		revision = None
	
	outmk = open(mkname, 'w')
	outmc = open(mcname, 'w')
	
	outmk.write('#########################################\n')
	outmk.write('## AUTO-GENERATED FILE, DO NOT EDIT!!! ##\n')
	outmk.write('#########################################\n\n')
	
	outmc.write('/***************************************\n')
	outmc.write(' * AUTO-GENERATED FILE, DO NOT EDIT!!! *\n')
	outmc.write(' ***************************************/\n\n')
	
	defs = 'CONFIG_DEFS ='
	
	for varname, vartype, name, choices, cond in rules:
		if cond and (not check_condition(cond, config, rules)):
			continue
		
		if not varname in config:
			value = ''
		else:
			value = config[varname]
			if (value == '*'):
				value = 'y'
		
		outmk.write('# %s\n%s = %s\n\n' % (name, varname, value))
		
		if vartype in ["y", "n", "y/n", "n/y"]:
			if value == "y":
				outmc.write('/* %s */\n#define %s\n\n' % (name, varname))
				defs += ' -D%s' % varname
		else:
			outmc.write('/* %s */\n#define %s %s\n#define %s_%s\n\n' % (name, varname, value, varname, value))
			defs += ' -D%s=%s -D%s_%s' % (varname, value, varname, value)
	
	if revision is not None:
		outmk.write('REVISION = %s\n' % revision)
		outmc.write('#define REVISION %s\n' % revision)
		defs += ' "-DREVISION=%s"' % revision
	
	outmk.write('TIMESTAMP = %s\n' % timestamp)
	outmc.write('#define TIMESTAMP %s\n' % timestamp)
	defs += ' "-DTIMESTAMP=%s"\n' % timestamp
	
	outmk.write(defs)
	
	outmk.close()
	outmc.close()

def sorted_dir(root):
	list = os.listdir(root)
	list.sort()
	return list

## Ask user to choose a configuration profile.
#
def choose_profile(root, fname, screen, config):
	options = []
	opt2path = {}
	cnt = 0
	
	# Look for profiles
	for name in sorted_dir(root):
		path = os.path.join(root, name)
		canon = os.path.join(path, fname)
		
		if os.path.isdir(path) and os.path.exists(canon) and os.path.isfile(canon):
			subprofile = False
			
			# Look for subprofiles
			for subname in sorted_dir(path):
				subpath = os.path.join(path, subname)
				subcanon = os.path.join(subpath, fname)
				
				if os.path.isdir(subpath) and os.path.exists(subcanon) and os.path.isfile(subcanon):
					subprofile = True
					options.append("%s (%s)" % (name, subname))
					opt2path[cnt] = [name, subname]
					cnt += 1
			
			if not subprofile:
				options.append(name)
				opt2path[cnt] = [name]
				cnt += 1
	
	(button, value) = xtui.choice_window(screen, 'Load preconfigured defaults', 'Choose configuration profile', options, None)
	
	if button == 'cancel':
		return None
	
	return opt2path[value]

## Read presets from a configuration profile.
#
# @param profile Profile to load from (a list of string components)
# @param config  Output configuration
#
def read_presets(profile, config):
	path = os.path.join(PRESETS_DIR, profile[0], MAKEFILE)
	read_config(path, config)
	
	if len(profile) > 1:
		path = os.path.join(PRESETS_DIR, profile[0], profile[1], MAKEFILE)
		read_config(path, config)

## Parse profile name (relative OS path) into a list of components.
#
# @param profile_name Relative path (using OS separator)
# @return             List of components
#
def parse_profile_name(profile_name):
	profile = []
	
	head, tail = os.path.split(profile_name)
	if head != '':
		profile.append(head)
	
	profile.append(tail)
	return profile

def main():
	profile = None
	config = {}
	rules = []
	
	# Parse rules file
	parse_rules(RULES_FILE, rules)
	
	# Input configuration file can be specified on command line
	# otherwise configuration from previous run is used.
	if len(sys.argv) >= 4:
		profile = parse_profile_name(sys.argv[3])
		read_presets(profile, config)
	elif os.path.exists(MAKEFILE):
		read_config(MAKEFILE, config)
	
	# Default mode: check values and regenerate configuration files
	if (len(sys.argv) >= 3) and (sys.argv[2] == 'default'):
		if (infer_verify_choices(config, rules)):
			preprocess_config(config, rules)
			create_output(MAKEFILE, MACROS, config, rules)
			return 0
	
	# Hands-off mode: check values and regenerate configuration files,
	# but no interactive fallback
	if (len(sys.argv) >= 3) and (sys.argv[2] == 'hands-off'):
		# We deliberately test sys.argv >= 4 because we do not want
		# to read implicitly any possible previous run configuration
		if len(sys.argv) < 4:
			sys.stderr.write("Configuration error: No presets specified\n")
			return 2
		
		if (infer_verify_choices(config, rules)):
			preprocess_config(config, rules)
			create_output(MAKEFILE, MACROS, config, rules)
			return 0
		
		sys.stderr.write("Configuration error: The presets are ambiguous\n")
		return 1
	
	# Check mode: only check configuration
	if (len(sys.argv) >= 3) and (sys.argv[2] == 'check'):
		if infer_verify_choices(config, rules):
			return 0
		return 1
	
	screen = xtui.screen_init()
	try:
		selname = None
		position = None
		while True:
			
			# Cancel out all values which have to be deduced
			for varname, vartype, name, choices, cond in rules:
				if (vartype == 'y') and (varname in config) and (config[varname] == '*'):
					config[varname] = None
			
			options = []
			opt2row = {}
			cnt = 1
			
			options.append("  --- Load preconfigured defaults ... ")
			
			for rule in rules:
				varname, vartype, name, choices, cond = rule
				
				if cond and (not check_condition(cond, config, rules)):
					continue
				
				if varname == selname:
					position = cnt
				
				if not varname in config:
					value = None
				else:
					value = config[varname]
				
				if not validate_rule_value(rule, value):
					value = None
				
				default = get_default_rule(rule)
				
				#
				# If we don't have a value but we do have
				# a default, use it.
				#
				if value == None and default != None:
					value = default
					config[varname] = default
				
				option = get_rule_option(rule, value)
				if option != None:
					options.append(option)
				else:
					continue
				
				opt2row[cnt] = (varname, vartype, name, choices)
				
				cnt += 1
			
			if (position != None) and (position >= len(options)):
				position = None
			
			(button, value) = xtui.choice_window(screen, 'HelenOS configuration', 'Choose configuration option', options, position)
			
			if button == 'cancel':
				return 'Configuration canceled'
			
			if button == 'done':
				if (infer_verify_choices(config, rules)):
					break
				else:
					xtui.error_dialog(screen, 'Error', 'Some options have still undefined values. These options are marked with the "?" sign.')
					continue
			
			if value == 0:
				profile = choose_profile(PRESETS_DIR, MAKEFILE, screen, config)
				if profile != None:
					read_presets(profile, config)
				position = 1
				continue
			
			position = None
			if not value in opt2row:
				raise RuntimeError("Error selecting value: %s" % value)
			
			(selname, seltype, name, choices) = opt2row[value]
			
			if not selname in config:
				value = None
			else:
				value = config[selname]
			
			if seltype == 'choice':
				config[selname] = subchoice(screen, name, choices, value)
			elif (seltype == 'y/n') or (seltype == 'n/y'):
				if config[selname] == 'y':
					config[selname] = 'n'
				else:
					config[selname] = 'y'
	finally:
		xtui.screen_done(screen)
	
	preprocess_config(config, rules)
	create_output(MAKEFILE, MACROS, config, rules)
	return 0

if __name__ == '__main__':
	sys.exit(main())