-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmenuconfig.py
More file actions
executable file
·9496 lines (7419 loc) · 320 KB
/
menuconfig.py
File metadata and controls
executable file
·9496 lines (7419 loc) · 320 KB
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) 2018-2019, Nordic Semiconductor ASA and Ulf Magnusson
# SPDX-License-Identifier: ISC
from __future__ import print_function
import os
import sys
_IS_WINDOWS = os.name == "nt" # Are we running on Windows?
try:
import curses
except ImportError as e:
if not _IS_WINDOWS:
raise
sys.exit("""\
menuconfig failed to import the standard Python 'curses' library. Try
installing a package like windows-curses
(https://github.com/zephyrproject-rtos/windows-curses) by running this command
in cmd.exe:
pip install windows-curses
Starting with Kconfiglib 13.0.0, windows-curses is no longer automatically
installed when installing Kconfiglib via pip on Windows (because it breaks
installation on MSYS2).
Exception:
{}: {}""".format(type(e).__name__, e))
import errno
import locale
import re
import textwrap
import errno
import importlib
import os
import re
import sys
# Get rid of some attribute lookups. These are obvious in context.
from glob import iglob
from os.path import dirname, exists, expandvars, islink, join, realpath
VERSION = (14, 1, 0)
class Kconfig(object):
__slots__ = (
"_encoding",
"_functions",
"_set_match",
"_srctree_prefix",
"_unset_match",
"_warn_assign_no_prompt",
"choices",
"comments",
"config_header",
"config_prefix",
"const_syms",
"defconfig_list",
"defined_syms",
"env_vars",
"header_header",
"kconfig_filenames",
"m",
"menus",
"missing_syms",
"modules",
"n",
"named_choices",
"srctree",
"syms",
"top_node",
"unique_choices",
"unique_defined_syms",
"variables",
"warn",
"warn_assign_override",
"warn_assign_redun",
"warn_assign_undef",
"warn_to_stderr",
"warnings",
"y",
# Parsing-related
"_parsing_kconfigs",
"_readline",
"filename",
"linenr",
"_include_path",
"_filestack",
"_line",
"_tokens",
"_tokens_i",
"_reuse_tokens",
)
#
# Public interface
#
def __init__(self, filename="Kconfig", warn=True, warn_to_stderr=True,
encoding="utf-8", suppress_traceback=False):
"""
Creates a new Kconfig object by parsing Kconfig files.
Note that Kconfig files are not the same as .config files (which store
configuration symbol values).
See the module docstring for some environment variables that influence
default warning settings (KCONFIG_WARN_UNDEF and
KCONFIG_WARN_UNDEF_ASSIGN).
Raises KconfigError on syntax/semantic errors, and OSError or (possibly
a subclass of) IOError on IO errors ('errno', 'strerror', and
'filename' are available). Note that IOError is an alias for OSError on
Python 3, so it's enough to catch OSError there. If you need Python 2/3
compatibility, it's easiest to catch EnvironmentError, which is a
common base class of OSError/IOError on Python 2 and an alias for
OSError on Python 3.
filename (default: "Kconfig"):
The Kconfig file to load. For the Linux kernel, you'll want "Kconfig"
from the top-level directory, as environment variables will make sure
the right Kconfig is included from there (arch/$SRCARCH/Kconfig as of
writing).
If $srctree is set, 'filename' will be looked up relative to it.
$srctree is also used to look up source'd files within Kconfig files.
See the class documentation.
If you are using Kconfiglib via 'make scriptconfig', the filename of
the base base Kconfig file will be in sys.argv[1]. It's currently
always "Kconfig" in practice.
warn (default: True):
True if warnings related to this configuration should be generated.
This can be changed later by setting Kconfig.warn to True/False. It
is provided as a constructor argument since warnings might be
generated during parsing.
See the other Kconfig.warn_* variables as well, which enable or
suppress certain warnings when warnings are enabled.
All generated warnings are added to the Kconfig.warnings list. See
the class documentation.
warn_to_stderr (default: True):
True if warnings should be printed to stderr in addition to being
added to Kconfig.warnings.
This can be changed later by setting Kconfig.warn_to_stderr to
True/False.
encoding (default: "utf-8"):
The encoding to use when reading and writing files, and when decoding
output from commands run via $(shell). If None, the encoding
specified in the current locale will be used.
The "utf-8" default avoids exceptions on systems that are configured
to use the C locale, which implies an ASCII encoding.
This parameter has no effect on Python 2, due to implementation
issues (regular strings turning into Unicode strings, which are
distinct in Python 2). Python 2 doesn't decode regular strings
anyway.
Related PEP: https://www.python.org/dev/peps/pep-0538/
suppress_traceback (default: False):
Helper for tools. When True, any EnvironmentError or KconfigError
generated during parsing is caught, the exception message is printed
to stderr together with the command name, and sys.exit(1) is called
(which generates SystemExit).
This hides the Python traceback for "expected" errors like syntax
errors in Kconfig files.
Other exceptions besides EnvironmentError and KconfigError are still
propagated when suppress_traceback is True.
"""
try:
self._init(filename, warn, warn_to_stderr, encoding)
except (EnvironmentError, KconfigError) as e:
if suppress_traceback:
cmd = sys.argv[0] # Empty string if missing
if cmd:
cmd += ": "
# Some long exception messages have extra newlines for better
# formatting when reported as an unhandled exception. Strip
# them here.
sys.exit(cmd + str(e).strip())
raise
def _init(self, filename, warn, warn_to_stderr, encoding):
# See __init__()
self._encoding = encoding
self.srctree = os.getenv("srctree", "")
# A prefix we can reliably strip from glob() results to get a filename
# relative to $srctree. relpath() can cause issues for symlinks,
# because it assumes symlink/../foo is the same as foo/.
self._srctree_prefix = realpath(self.srctree) + os.sep
self.warn = warn
self.warn_to_stderr = warn_to_stderr
self.warn_assign_undef = os.getenv("KCONFIG_WARN_UNDEF_ASSIGN") == "y"
self.warn_assign_override = True
self.warn_assign_redun = True
self._warn_assign_no_prompt = True
self.warnings = []
self.config_prefix = os.getenv("CONFIG_", "CONFIG_")
# Regular expressions for parsing .config files
self._set_match = _re_match(self.config_prefix + r"([^=]+)=(.*)")
self._unset_match = _re_match(r"# {}([^ ]+) is not set".format(
self.config_prefix))
self.config_header = os.getenv("KCONFIG_CONFIG_HEADER", "")
self.header_header = os.getenv("KCONFIG_AUTOHEADER_HEADER", "")
self.syms = {}
self.const_syms = {}
self.defined_syms = []
self.missing_syms = []
self.named_choices = {}
self.choices = []
self.menus = []
self.comments = []
for nmy in "n", "m", "y":
sym = Symbol()
sym.kconfig = self
sym.name = nmy
sym.is_constant = True
sym.orig_type = TRISTATE
sym._cached_tri_val = STR_TO_TRI[nmy]
self.const_syms[nmy] = sym
self.n = self.const_syms["n"]
self.m = self.const_syms["m"]
self.y = self.const_syms["y"]
# Make n/m/y well-formed symbols
for nmy in "n", "m", "y":
sym = self.const_syms[nmy]
sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
# Maps preprocessor variables names to Variable instances
self.variables = {}
# Predefined preprocessor functions, with min/max number of arguments
self._functions = {
"info": (_info_fn, 1, 1),
"error-if": (_error_if_fn, 2, 2),
"filename": (_filename_fn, 0, 0),
"lineno": (_lineno_fn, 0, 0),
"shell": (_shell_fn, 1, 1),
"warning-if": (_warning_if_fn, 2, 2),
}
# Add any user-defined preprocessor functions
try:
self._functions.update(
importlib.import_module(
os.getenv("KCONFIG_FUNCTIONS", "kconfigfunctions")
).functions)
except ImportError:
pass
# This determines whether previously unseen symbols are registered.
# They shouldn't be if we parse expressions after parsing, as part of
# Kconfig.eval_string().
self._parsing_kconfigs = True
self.modules = self._lookup_sym("MODULES")
self.defconfig_list = None
self.top_node = MenuNode()
self.top_node.kconfig = self
self.top_node.item = MENU
self.top_node.is_menuconfig = True
self.top_node.visibility = self.y
self.top_node.prompt = ("Main menu", self.y)
self.top_node.parent = None
self.top_node.dep = self.y
self.top_node.filename = filename
self.top_node.linenr = 1
self.top_node.include_path = ()
# Parse the Kconfig files
# Not used internally. Provided as a convenience.
self.kconfig_filenames = [filename]
self.env_vars = set()
# Keeps track of the location in the parent Kconfig files. Kconfig
# files usually source other Kconfig files. See _enter_file().
self._filestack = []
self._include_path = ()
# The current parsing location
self.filename = filename
self.linenr = 0
# Used to avoid retokenizing lines when we discover that they're not
# part of the construct currently being parsed. This is kinda like an
# unget operation.
self._reuse_tokens = False
# Open the top-level Kconfig file. Store the readline() method directly
# as a small optimization.
self._readline = self._open(join(self.srctree, filename), "r").readline
try:
# Parse the Kconfig files. Returns the last node, which we
# terminate with '.next = None'.
self._parse_block(None, self.top_node, self.top_node).next = None
self.top_node.list = self.top_node.next
self.top_node.next = None
except UnicodeDecodeError as e:
_decoding_error(e, self.filename)
# Close the top-level Kconfig file. __self__ fetches the 'file' object
# for the method.
self._readline.__self__.close()
self._parsing_kconfigs = False
# Do various menu tree post-processing
self._finalize_node(self.top_node, self.y)
self.unique_defined_syms = _ordered_unique(self.defined_syms)
self.unique_choices = _ordered_unique(self.choices)
# Do sanity checks. Some of these depend on everything being finalized.
self._check_sym_sanity()
self._check_choice_sanity()
# KCONFIG_STRICT is an older alias for KCONFIG_WARN_UNDEF, supported
# for backwards compatibility
if os.getenv("KCONFIG_WARN_UNDEF") == "y" or \
os.getenv("KCONFIG_STRICT") == "y":
self._check_undef_syms()
# Build Symbol._dependents for all symbols and choices
self._build_dep()
# Check for dependency loops
check_dep_loop_sym = _check_dep_loop_sym # Micro-optimization
for sym in self.unique_defined_syms:
check_dep_loop_sym(sym, False)
# Add extra dependencies from choices to choice symbols that get
# awkward during dependency loop detection
self._add_choice_deps()
@property
def mainmenu_text(self):
"""
See the class documentation.
"""
return self.top_node.prompt[0]
@property
def defconfig_filename(self):
"""
See the class documentation.
"""
if self.defconfig_list:
for filename, cond in self.defconfig_list.defaults:
if expr_value(cond):
try:
with self._open_config(filename.str_value) as f:
return f.name
except EnvironmentError:
continue
return None
def load_config(self, filename=None, replace=True, verbose=None):
"""
Loads symbol values from a file in the .config format. Equivalent to
calling Symbol.set_value() to set each of the values.
"# CONFIG_FOO is not set" within a .config file sets the user value of
FOO to n. The C tools work the same way.
For each symbol, the Symbol.user_value attribute holds the value the
symbol was assigned in the .config file (if any). The user value might
differ from Symbol.str/tri_value if there are unsatisfied dependencies.
Calling this function also updates the Kconfig.missing_syms attribute
with a list of all assignments to undefined symbols within the
configuration file. Kconfig.missing_syms is cleared if 'replace' is
True, and appended to otherwise. See the documentation for
Kconfig.missing_syms as well.
See the Kconfig.__init__() docstring for raised exceptions
(OSError/IOError). KconfigError is never raised here.
filename (default: None):
Path to load configuration from (a string). Respects $srctree if set
(see the class documentation).
If 'filename' is None (the default), the configuration file to load
(if any) is calculated automatically, giving the behavior you'd
usually want:
1. If the KCONFIG_CONFIG environment variable is set, it gives the
path to the configuration file to load. Otherwise, ".config" is
used. See standard_config_filename().
2. If the path from (1.) doesn't exist, the configuration file
given by kconf.defconfig_filename is loaded instead, which is
derived from the 'option defconfig_list' symbol.
3. If (1.) and (2.) fail to find a configuration file to load, no
configuration file is loaded, and symbols retain their current
values (e.g., their default values). This is not an error.
See the return value as well.
replace (default: True):
If True, all existing user values will be cleared before loading the
.config. Pass False to merge configurations.
verbose (default: None):
Limited backwards compatibility to prevent crashes. A warning is
printed if anything but None is passed.
Prior to Kconfiglib 12.0.0, this option enabled printing of messages
to stdout when 'filename' was None. A message is (always) returned
now instead, which is more flexible.
Will probably be removed in some future version.
Returns a string with a message saying which file got loaded (or
possibly that no file got loaded, when 'filename' is None). This is
meant to reduce boilerplate in tools, which can do e.g.
print(kconf.load_config()). The returned message distinguishes between
loading (replace == True) and merging (replace == False).
"""
if verbose is not None:
_warn_verbose_deprecated("load_config")
msg = None
if filename is None:
filename = standard_config_filename()
if not exists(filename) and \
not exists(join(self.srctree, filename)):
defconfig = self.defconfig_filename
if defconfig is None:
return "Using default symbol values (no '{}')" \
.format(filename)
msg = " default configuration '{}' (no '{}')" \
.format(defconfig, filename)
filename = defconfig
if not msg:
msg = " configuration '{}'".format(filename)
# Disable the warning about assigning to symbols without prompts. This
# is normal and expected within a .config file.
self._warn_assign_no_prompt = False
# This stub only exists to make sure _warn_assign_no_prompt gets
# reenabled
try:
self._load_config(filename, replace)
except UnicodeDecodeError as e:
_decoding_error(e, filename)
finally:
self._warn_assign_no_prompt = True
return ("Loaded" if replace else "Merged") + msg
def _load_config(self, filename, replace):
with self._open_config(filename) as f:
if replace:
self.missing_syms = []
# If we're replacing the configuration, keep track of which
# symbols and choices got set so that we can unset the rest
# later. This avoids invalidating everything and is faster.
# Another benefit is that invalidation must be rock solid for
# it to work, making it a good test.
for sym in self.unique_defined_syms:
sym._was_set = False
for choice in self.unique_choices:
choice._was_set = False
# Small optimizations
set_match = self._set_match
unset_match = self._unset_match
get_sym = self.syms.get
for linenr, line in enumerate(f, 1):
# The C tools ignore trailing whitespace
line = line.rstrip()
match = set_match(line)
if match:
name, val = match.groups()
sym = get_sym(name)
if not sym or not sym.nodes:
self._undef_assign(name, val, filename, linenr)
continue
if sym.orig_type in _BOOL_TRISTATE:
# The C implementation only checks the first character
# to the right of '=', for whatever reason
if not (sym.orig_type is BOOL
and val.startswith(("y", "n")) or
sym.orig_type is TRISTATE
and val.startswith(("y", "m", "n"))):
self._warn("'{}' is not a valid value for the {} "
"symbol {}. Assignment ignored."
.format(val, TYPE_TO_STR[sym.orig_type],
sym.name_and_loc),
filename, linenr)
continue
val = val[0]
if sym.choice and val != "n":
# During .config loading, we infer the mode of the
# choice from the kind of values that are assigned
# to the choice symbols
prev_mode = sym.choice.user_value
if prev_mode is not None and \
TRI_TO_STR[prev_mode] != val:
self._warn("both m and y assigned to symbols "
"within the same choice",
filename, linenr)
# Set the choice's mode
sym.choice.set_value(val)
elif sym.orig_type is STRING:
match = _conf_string_match(val)
if not match:
self._warn("malformed string literal in "
"assignment to {}. Assignment ignored."
.format(sym.name_and_loc),
filename, linenr)
continue
val = unescape(match.group(1))
else:
match = unset_match(line)
if not match:
# Print a warning for lines that match neither
# set_match() nor unset_match() and that are not blank
# lines or comments. 'line' has already been
# rstrip()'d, so blank lines show up as "" here.
if line and not line.lstrip().startswith("#"):
self._warn("ignoring malformed line '{}'"
.format(line),
filename, linenr)
continue
name = match.group(1)
sym = get_sym(name)
if not sym or not sym.nodes:
self._undef_assign(name, "n", filename, linenr)
continue
if sym.orig_type not in _BOOL_TRISTATE:
continue
val = "n"
# Done parsing the assignment. Set the value.
if sym._was_set:
self._assigned_twice(sym, val, filename, linenr)
sym.set_value(val)
if replace:
# If we're replacing the configuration, unset the symbols that
# didn't get set
for sym in self.unique_defined_syms:
if not sym._was_set:
sym.unset_value()
for choice in self.unique_choices:
if not choice._was_set:
choice.unset_value()
def _undef_assign(self, name, val, filename, linenr):
# Called for assignments to undefined symbols during .config loading
self.missing_syms.append((name, val))
if self.warn_assign_undef:
self._warn(
"attempt to assign the value '{}' to the undefined symbol {}"
.format(val, name), filename, linenr)
def _assigned_twice(self, sym, new_val, filename, linenr):
# Called when a symbol is assigned more than once in a .config file
# Use strings for bool/tristate user values in the warning
if sym.orig_type in _BOOL_TRISTATE:
user_val = TRI_TO_STR[sym.user_value]
else:
user_val = sym.user_value
msg = '{} set more than once. Old value "{}", new value "{}".'.format(
sym.name_and_loc, user_val, new_val)
if user_val == new_val:
if self.warn_assign_redun:
self._warn(msg, filename, linenr)
elif self.warn_assign_override:
self._warn(msg, filename, linenr)
def load_allconfig(self, filename):
"""
Helper for all*config. Loads (merges) the configuration file specified
by KCONFIG_ALLCONFIG, if any. See Documentation/kbuild/kconfig.txt in
the Linux kernel.
Disables warnings for duplicated assignments within configuration files
for the duration of the call
(kconf.warn_assign_override/warn_assign_redun = False), and restores
the previous warning settings at the end. The KCONFIG_ALLCONFIG
configuration file is expected to override symbols.
Exits with sys.exit() (which raises a SystemExit exception) and prints
an error to stderr if KCONFIG_ALLCONFIG is set but the configuration
file can't be opened.
filename:
Command-specific configuration filename - "allyes.config",
"allno.config", etc.
"""
load_allconfig(self, filename)
def write_autoconf(self, filename=None, header=None):
r"""
Writes out symbol values as a C header file, matching the format used
by include/generated/autoconf.h in the kernel.
The ordering of the #defines matches the one generated by
write_config(). The order in the C implementation depends on the hash
table implementation as of writing, and so won't match.
If 'filename' exists and its contents is identical to what would get
written out, it is left untouched. This avoids updating file metadata
like the modification time and possibly triggering redundant work in
build tools.
filename (default: None):
Path to write header to.
If None (the default), the path in the environment variable
KCONFIG_AUTOHEADER is used if set, and "include/generated/autoconf.h"
otherwise. This is compatible with the C tools.
header (default: None):
Text inserted verbatim at the beginning of the file. You would
usually want it enclosed in '/* */' to make it a C comment, and
include a trailing newline.
If None (the default), the value of the environment variable
KCONFIG_AUTOHEADER_HEADER had when the Kconfig instance was created
will be used if it was set, and no header otherwise. See the
Kconfig.header_header attribute.
Returns a string with a message saying that the header got saved, or
that there were no changes to it. This is meant to reduce boilerplate
in tools, which can do e.g. print(kconf.write_autoconf()).
"""
if filename is None:
filename = os.getenv("KCONFIG_AUTOHEADER",
"include/generated/autoconf.h")
if self._write_if_changed(filename, self._autoconf_contents(header)):
return "Kconfig header saved to '{}'".format(filename)
return "No change to Kconfig header in '{}'".format(filename)
def _autoconf_contents(self, header):
# write_autoconf() helper. Returns the contents to write as a string,
# with 'header' or KCONFIG_AUTOHEADER_HEADER at the beginning.
if header is None:
header = self.header_header
chunks = [header] # "".join()ed later
add = chunks.append
for sym in self.unique_defined_syms:
# _write_to_conf is determined when the value is calculated. This
# is a hidden function call due to property magic.
#
# Note: In client code, you can check if sym.config_string is empty
# instead, to avoid accessing the internal _write_to_conf variable
# (though it's likely to keep working).
val = sym.str_value
if not sym._write_to_conf:
continue
if sym.orig_type in _BOOL_TRISTATE:
if val == "y":
add("#define {}{} 1\n"
.format(self.config_prefix, sym.name))
elif val == "m":
add("#define {}{}_MODULE 1\n"
.format(self.config_prefix, sym.name))
elif val == "n":
add("#define {}{} 0\n"
.format(self.config_prefix, sym.name))
elif sym.orig_type is STRING:
add('#define {}{} "{}"\n'
.format(self.config_prefix, sym.name, escape(val)))
else: # sym.orig_type in _INT_HEX:
if sym.orig_type is HEX and \
not val.startswith(("0x", "0X")):
val = "0x" + val
add("#define {}{} {}\n"
.format(self.config_prefix, sym.name, val))
return "".join(chunks)
def _config_mk_write(self, header):
if header is None:
header = self.header_header
chunks = [header] # "".join()ed later
add = chunks.append
for sym in self.unique_defined_syms:
# _write_to_conf is determined when the value is calculated. This
# is a hidden function call due to property magic.
#
# Note: In client code, you can check if sym.config_string is empty
# instead, to avoid accessing the internal _write_to_conf variable
# (though it's likely to keep working).
val = sym.str_value
if not sym._write_to_conf:
continue
if sym.orig_type in _BOOL_TRISTATE:
if val == "y":
add("{}{}=1\n".format(self.config_prefix, sym.name))
elif val == "n":
add("{}{}=0\n".format(self.config_prefix, sym.name))
elif sym.orig_type is STRING:
add('{}{}="{}"\n'
.format(self.config_prefix, sym.name, escape(val)))
return "".join(chunks)
def write_config(self, filename=None, header=None, save_old=True,
verbose=None):
r"""
Writes out symbol values in the .config format. The format matches the
C implementation, including ordering.
Symbols appear in the same order in generated .config files as they do
in the Kconfig files. For symbols defined in multiple locations, a
single assignment is written out corresponding to the first location
where the symbol is defined.
See the 'Intro to symbol values' section in the module docstring to
understand which symbols get written out.
If 'filename' exists and its contents is identical to what would get
written out, it is left untouched. This avoids updating file metadata
like the modification time and possibly triggering redundant work in
build tools.
See the Kconfig.__init__() docstring for raised exceptions
(OSError/IOError). KconfigError is never raised here.
filename (default: None):
Path to write configuration to (a string).
If None (the default), the path in the environment variable
KCONFIG_CONFIG is used if set, and ".config" otherwise. See
standard_config_filename().
header (default: None):
Text inserted verbatim at the beginning of the file. You would
usually want each line to start with '#' to make it a comment, and
include a trailing newline.
if None (the default), the value of the environment variable
KCONFIG_CONFIG_HEADER had when the Kconfig instance was created will
be used if it was set, and no header otherwise. See the
Kconfig.config_header attribute.
save_old (default: True):
If True and <filename> already exists, a copy of it will be saved to
<filename>.old in the same directory before the new configuration is
written.
Errors are silently ignored if <filename>.old cannot be written (e.g.
due to being a directory, or <filename> being something like
/dev/null).
verbose (default: None):
Limited backwards compatibility to prevent crashes. A warning is
printed if anything but None is passed.
Prior to Kconfiglib 12.0.0, this option enabled printing of messages
to stdout when 'filename' was None. A message is (always) returned
now instead, which is more flexible.
Will probably be removed in some future version.
Returns a string with a message saying which file got saved. This is
meant to reduce boilerplate in tools, which can do e.g.
print(kconf.write_config()).
"""
if verbose is not None:
_warn_verbose_deprecated("write_config")
if filename is None:
filename = standard_config_filename()
contents = self._config_contents(header)
if self._contents_eq(filename, contents):
return "No change to configuration in '{}'".format(filename)
if save_old:
_save_old(filename)
with self._open(filename, "w") as f:
f.write(contents)
# write the autoconf file
self.write_autoconf('include/fpvm/config.h')
if self._write_if_changed('config.mk', self._config_mk_write(header)):
return "config.mk saved".format(filename)
return "Configuration saved to '{}'".format(filename)
def _config_contents(self, header):
# write_config() helper. Returns the contents to write as a string,
# with 'header' or KCONFIG_CONFIG_HEADER at the beginning.
#
# More memory friendly would be to 'yield' the strings and
# "".join(_config_contents()), but it was a bit slower on my system.
# node_iter() was used here before commit 3aea9f7 ("Add '# end of
# <menu>' after menus in .config"). Those comments get tricky to
# implement with it.
for sym in self.unique_defined_syms:
sym._visited = False
if header is None:
header = self.config_header
chunks = [header] # "".join()ed later
add = chunks.append
# Did we just print an '# end of ...' comment?
after_end_comment = False
node = self.top_node
while 1:
# Jump to the next node with an iterative tree walk
if node.list:
node = node.list
elif node.next:
node = node.next
else:
while node.parent:
node = node.parent
# Add a comment when leaving visible menus
if node.item is MENU and expr_value(node.dep) and \
expr_value(node.visibility) and \
node is not self.top_node:
add("# end of {}\n".format(node.prompt[0]))
after_end_comment = True
if node.next:
node = node.next
break
else:
# No more nodes
return "".join(chunks)
# Generate configuration output for the node
item = node.item
if item.__class__ is Symbol:
if item._visited:
continue
item._visited = True
conf_string = item.config_string
if not conf_string:
continue
if after_end_comment:
# Add a blank line before the first symbol printed after an
# '# end of ...' comment
after_end_comment = False
add("\n")
add(conf_string)
elif expr_value(node.dep) and \
((item is MENU and expr_value(node.visibility)) or
item is COMMENT):
add("\n#\n# {}\n#\n".format(node.prompt[0]))
after_end_comment = False
def write_min_config(self, filename, header=None):
"""
Writes out a "minimal" configuration file, omitting symbols whose value
matches their default value. The format matches the one produced by
'make savedefconfig'.
The resulting configuration file is incomplete, but a complete
configuration can be derived from it by loading it. Minimal
configuration files can serve as a more manageable configuration format
compared to a "full" .config file, especially when configurations files
are merged or edited by hand.
See the Kconfig.__init__() docstring for raised exceptions
(OSError/IOError). KconfigError is never raised here.
filename:
Path to write minimal configuration to.
header (default: None):
Text inserted verbatim at the beginning of the file. You would
usually want each line to start with '#' to make it a comment, and
include a final terminating newline.
if None (the default), the value of the environment variable
KCONFIG_CONFIG_HEADER had when the Kconfig instance was created will
be used if it was set, and no header otherwise. See the
Kconfig.config_header attribute.
Returns a string with a message saying the minimal configuration got
saved, or that there were no changes to it. This is meant to reduce
boilerplate in tools, which can do e.g.
print(kconf.write_min_config()).
"""
if self._write_if_changed(filename, self._min_config_contents(header)):
return "Minimal configuration saved to '{}'".format(filename)
return "No change to minimal configuration in '{}'".format(filename)
def _min_config_contents(self, header):
# write_min_config() helper. Returns the contents to write as a string,
# with 'header' or KCONFIG_CONFIG_HEADER at the beginning.
if header is None:
header = self.config_header
chunks = [header] # "".join()ed later
add = chunks.append
for sym in self.unique_defined_syms:
# Skip symbols that cannot be changed. Only check
# non-choice symbols, as selects don't affect choice
# symbols.
if not sym.choice and \
sym.visibility <= expr_value(sym.rev_dep):
continue
# Skip symbols whose value matches their default
if sym.str_value == sym._str_default():
continue
# Skip symbols that would be selected by default in a
# choice, unless the choice is optional or the symbol type
# isn't bool (it might be possible to set the choice mode
# to n or the symbol to m in those cases).
if sym.choice and \