source: kernel-config/kernel-config.py@ cddcdb14

12.0 12.1 ken/TL2024 ken/tuningfonts lazarus plabs/newcss python3.11 rahul/power-profiles-daemon renodr/vulkan-addition trunk xry111/llvm18
Last change on this file since cddcdb14 was 1cf24363, checked in by Xi Ruoyao <xry111@…>, 11 months ago

introduction: Use new kernel configuration rendering in conventions

  • Property mode set to 100755
File size: 8.7 KB
Line 
1#!/usr/bin/env python3
2
3# SPDX-License-Identifier: MIT
4# Copyright 2023 The LFS Editors
5
6# Stupid script to render "mconf"-style kernel configuration
7# Usage: kernel-config.py [path to kernel tree] [needed config].toml
8# The toml file should be like:
9# for bool and tristate:
10# EXT4="*"
11# DRM="*M"
12# EXPERT=" "
13# DRM_I915="*M"
14# for choice:
15# HIGHMEM64G="X"
16# an entry with comment:
17# DRM_I915 = { value = " *M", comment = "for i915, crocus, or iris" }
18
19choice_bit = 1 << 30
20ind0 = 0
21ind1 = 0
22menu_id = 1
23stack = []
24if_stack = []
25
26expand_var_mp = { 'SRCARCH': 'x86' }
27main_dep = {}
28
29def expand_var(s):
30 for k in expand_var_mp:
31 s = s.replace('$(' + k + ')', expand_var_mp[k])
32 return s
33
34def pop_stack(cond):
35 global ind0, ind1, stack
36 assert(cond(stack[-1][0]))
37 s, i0, i1, _ = stack[-1]
38 stack = stack[:-1]
39 ind0 -= i0
40 ind1 -= i1
41
42def pop_stack_while(cond):
43 while stack and cond(stack[-1][0]):
44 pop_stack(cond)
45
46def cur_menu():
47 global stack
48 return stack[-1][3] if stack else 0
49
50def cur_if():
51 global if_stack
52 return if_stack[-1][:] if if_stack else []
53
54def clean_dep(d):
55 d = d.strip()
56 if d.endswith('=y') or d.endswith('=M'):
57 d = d[:-2]
58 elif d.endswith(' != ""'):
59 d = d[:-6]
60 return d
61
62def parse_config(buf):
63 global ind0, ind1, stack, menu_id
64 is_menu = buf[0].startswith('menu')
65 is_nonconfig_menu = buf[0].startswith('menu ')
66 key = None if is_nonconfig_menu else buf[0].split()[1].strip()
67 title = buf[0][len('menu '):] if is_nonconfig_menu else None
68 deps = ['menu'] + cur_if()
69 klass = None
70
71 for line in buf[1:]:
72 line = line.strip()
73 if line.startswith('depends on '):
74 new_deps = line[len('depends on '):].split('&&')
75 deps += [clean_dep(x) for x in new_deps]
76 elif line.startswith('prompt'):
77 title = line[len('prompt '):]
78 else:
79 for prefix in ['tristate', 'bool', 'string']:
80 if line.startswith(prefix + ' '):
81 title = line[len(prefix) + 1:]
82 klass = prefix
83 elif line == prefix:
84 klass = prefix
85 elif line.startswith('def_' + prefix + ' '):
86 klass = prefix
87 else:
88 continue
89
90 if '"' in line:
91 tail = line[line.rfind('"') + 1:].strip()
92 if tail[:3] == 'if ':
93 deps += [clean_dep(x) for x in tail[3:].split('&&')]
94
95 pop_stack_while(lambda x: x not in deps)
96
97 menu_id += is_menu
98 internal_key = key or menu_id
99 if stack:
100 fa = stack[-1][0]
101 if fa == 'menu':
102 fa = cur_menu() & ~choice_bit
103 main_dep[internal_key] = fa
104
105 val = known_config.get(key)
106 comment = None
107 forced = None
108
109 if type(val) == dict:
110 comment = val.get('comment')
111 forced = val.get('forced')
112 val = val['value']
113
114 klass = klass or 'string'
115 if title:
116 title = title.strip().lstrip('"')
117 title = title[:title.find('"')]
118
119 if not val:
120 pass
121 elif klass == 'string':
122 val = '(' + val + ')'
123 else:
124 assert((val == 'X') == bool(cur_menu() & choice_bit))
125 if (val == 'X'):
126 val = '(X)'
127 else:
128 val = list(val)
129 val.sort()
130 for c in val:
131 if c not in 'M* ' or (c == 'M' and klass != 'tristate'):
132 raise Exception('unknown setting %s for %s' % (c, key))
133 bracket = None
134 if klass == 'tristate' and forced != '*' :
135 bracket = '{}' if forced else '<>'
136 else:
137 bracket = '--' if forced else '[]'
138
139 val = bracket[0] + '/'.join(val) + bracket[1]
140
141 arrow = ' --->' if is_menu else ''
142 r = [ind0, val, ind1, title, arrow, internal_key, cur_menu(), comment]
143
144 # Don't indent for untitled (internal) entries
145 x = 2 if title else 0
146
147 key = key or 'menu'
148 stack_ent = (key, 2, 0, menu_id) if is_menu else (key, 0, x, cur_menu())
149 ind0 += stack_ent[1]
150 ind1 += stack_ent[2]
151 stack += [stack_ent]
152
153 return r
154
155def parse_choice(buf):
156 global ind0, ind1, stack, menu_id
157 assert(buf[0] == 'choice\n')
158 title = ''
159 for line in buf:
160 line = line.strip()
161 if line.startswith('prompt '):
162 title = line[len('prompt '):].strip().strip('"')
163
164 menu_id += 1
165
166 if stack:
167 fa = stack[-1][0]
168 if fa == 'menu':
169 fa = cur_menu() & ~choice_bit
170 main_dep[menu_id] = fa
171
172 r = [ind0, None, ind1, title, ' --->', menu_id, cur_menu(), None]
173 stack += [('menu', 2, 0, menu_id | choice_bit)]
174 ind0 += 2
175 return r
176
177def load_kconfig(file):
178 global ind0, ind1, stack, path, menu_id, if_stack
179 r = []
180 config_buf = []
181 with open(path + file) as f:
182 for line in f:
183 if config_buf:
184 if not (line.startswith('\t') or line.startswith(' ')):
185 if config_buf[0] == 'choice\n':
186 r += [parse_choice(config_buf)]
187 else:
188 r += [parse_config(config_buf)]
189 config_buf = []
190 else:
191 config_buf += [line]
192 continue
193 if line.startswith('source') or line.startswith('\tsource'):
194 sub = expand_var(line.strip().split()[1].strip('"'))
195 r += load_kconfig(sub)
196 elif line.startswith('config') or line.startswith('menu'):
197 config_buf = [line]
198 elif line.startswith('choice'):
199 config_buf = [line]
200 elif line.startswith('endmenu') or line.startswith('endchoice'):
201 pop_stack_while(lambda x: x != 'menu')
202 pop_stack(lambda x: x == 'menu')
203 elif line.startswith('if '):
204 line = line[3:]
205 top = cur_if()
206 top += [x.strip() for x in line.split("&&")]
207 if_stack += [top]
208 elif line.startswith('endif'):
209 if_stack = if_stack[:-1]
210 return r
211
212known_config = {}
213
214def escape(x):
215 return x.replace('<', '&lt;').replace('>', '&gt;')
216
217from sys import argv
218import tomllib
219
220path = argv[1]
221if path[-1] != '/':
222 path += '/'
223with open(argv[2], 'rb') as f:
224 known_config = tomllib.load(f)
225
226r = load_kconfig('Kconfig')
227
228# Refcount all menus
229
230index_ikey = {}
231for i in reversed(range(len(r))):
232 index_ikey[r[i][5]] = i
233
234for i in reversed(range(len(r))):
235 if r[i][1] != None:
236 key = r[i][5]
237 fa = main_dep.get(key)
238 if not fa:
239 continue
240 j = index_ikey[fa]
241 if type(fa) == int or not r[j][3]:
242 # The main dependency is a menu or untitled magic entry,
243 # just mark it used
244 r[j][1] = ''
245 if r[j][1] is None:
246 raise Exception('[%s] needs unselected [%s]' % (key, fa))
247
248r = [i for i in r if i[1] != None and i[3]]
249
250# Now we are going to pretty-print r
251
252## Calculate the maximum value length for each menu
253max_val_len = {}
254for _, val, _, _, _, _, menu, _ in r:
255 x = max_val_len.get(menu) or 0
256 max_val_len[menu] = max(x, len(val))
257
258## Output
259
260max_line = 80
261buf = []
262
263done = [x[5] for x in r] + ['revision']
264for i in known_config:
265 if i not in done:
266 raise Exception("%s seems not exist" % i)
267
268for i0, val, i1, title, arrow, key, menu, comment in r:
269 rem = max_line
270
271 if val:
272 val += (max_val_len[menu] - len(val)) * ' '
273
274 rem -= i0 + i1 + bool(val) + len(val)
275 line = i0 * ' ' + escape(val) + (i1 + bool(val)) * ' '
276
277 rem -= len(arrow)
278
279 if len(title) > rem:
280 title = title[:rem - 3] + '...'
281
282 b = title.lstrip('YyMmNnHh')
283 a = title[:len(title) - len(b)]
284 b0 = "<emphasis role='blue'>" + escape(b[0]) + "</emphasis>"
285 line += escape(a) + b0 + escape(b[1:]) + escape(arrow)
286
287 rem -= len(title)
288
289 key = ' [' + key + ']' if type(key) == str else ''
290
291 if len(key) <= rem:
292 line += (rem - len(key)) * ' ' + key
293 else:
294 key = '... ' + key
295 line += '\n' + ' ' * (max_line - len(key)) + key
296 if type(comment) == str:
297 comment = [comment]
298 if comment:
299 comment = '\n'.join([' ' * i0 + '# ' + line for line in comment])
300 line = escape(comment) + ':\n' + line
301
302 buf += [line.rstrip()]
303
304from jinja2 import Template
305
306t = Template('''<?xml version="1.0" encoding="ISO-8859-1"?>
307<!DOCTYPE note PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
308 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
309<!-- Automatically generated by kernel-config.py
310 DO NOT EDIT! -->
311<screen{{ rev }}>{{ '\n'.join(buf) }}</screen>''')
312
313rev = known_config.get('revision')
314rev = ' revision="%s"' % rev if rev else ''
315print(t.render(rev = rev, buf = buf))
Note: See TracBrowser for help on using the repository browser.