Blame view
tools/genboardscfg.py
14.1 KB
2134342e5 tools/genboardscf... |
1 |
#!/usr/bin/env python2 |
3c08e8b85 tools: add genboa... |
2 3 4 5 6 7 8 |
# # Author: Masahiro Yamada <yamada.m@jp.panasonic.com> # # SPDX-License-Identifier: GPL-2.0+ # """ |
f6c8f38ec tools/genboardscf... |
9 |
Converter from Kconfig and MAINTAINERS to a board database. |
3c08e8b85 tools: add genboa... |
10 |
|
f6c8f38ec tools/genboardscf... |
11 |
Run 'tools/genboardscfg.py' to create a board database. |
3c08e8b85 tools: add genboa... |
12 13 |
Run 'tools/genboardscfg.py -h' for available options. |
2134342e5 tools/genboardscf... |
14 |
|
f6c8f38ec tools/genboardscf... |
15 |
Python 2.6 or later, but not Python 3.x is necessary to run this script. |
3c08e8b85 tools: add genboa... |
16 17 18 19 20 |
""" import errno import fnmatch import glob |
f6c8f38ec tools/genboardscf... |
21 |
import multiprocessing |
3c08e8b85 tools: add genboa... |
22 23 |
import optparse import os |
3c08e8b85 tools: add genboa... |
24 25 26 |
import sys import tempfile import time |
f6c8f38ec tools/genboardscf... |
27 28 |
sys.path.append(os.path.join(os.path.dirname(__file__), 'buildman')) import kconfiglib |
3c08e8b85 tools: add genboa... |
29 |
|
f6c8f38ec tools/genboardscf... |
30 31 32 33 |
### constant variables ### OUTPUT_FILE = 'boards.cfg' CONFIG_DIR = 'configs' SLEEP_TIME = 0.03 |
3c08e8b85 tools: add genboa... |
34 35 36 37 |
COMMENT_BLOCK = '''# # List of boards # Automatically generated by %s: don't edit # |
ca418dd74 tools/genboardscf... |
38 |
# Status, Arch, CPU, SoC, Vendor, Board, Target, Options, Maintainers |
3c08e8b85 tools: add genboa... |
39 40 41 42 |
''' % __file__ ### helper functions ### |
f6c8f38ec tools/genboardscf... |
43 44 |
def try_remove(f): """Remove a file ignoring 'No such file or directory' error.""" |
3c08e8b85 tools: add genboa... |
45 |
try: |
f6c8f38ec tools/genboardscf... |
46 47 48 49 50 |
os.remove(f) except OSError as exception: # Ignore 'No such file or directory' error if exception.errno != errno.ENOENT: raise |
3c08e8b85 tools: add genboa... |
51 52 53 54 55 |
def check_top_directory(): """Exit if we are not at the top of source directory.""" for f in ('README', 'Licenses'): if not os.path.exists(f): |
31e2141d5 tools, scripts: r... |
56 |
sys.exit('Please run at the top of source directory.') |
3c08e8b85 tools: add genboa... |
57 |
|
f6c8f38ec tools/genboardscf... |
58 59 |
def output_is_new(output): """Check if the output file is up to date. |
d1bf4afda tools/genboardscf... |
60 61 |
Returns: |
f6c8f38ec tools/genboardscf... |
62 |
True if the given output file exists and is newer than any of |
d1bf4afda tools/genboardscf... |
63 64 65 |
*_defconfig, MAINTAINERS and Kconfig*. False otherwise. """ try: |
f6c8f38ec tools/genboardscf... |
66 |
ctime = os.path.getctime(output) |
d1bf4afda tools/genboardscf... |
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
except OSError as exception: if exception.errno == errno.ENOENT: # return False on 'No such file or directory' error return False else: raise for (dirpath, dirnames, filenames) in os.walk(CONFIG_DIR): for filename in fnmatch.filter(filenames, '*_defconfig'): if fnmatch.fnmatch(filename, '.*'): continue filepath = os.path.join(dirpath, filename) if ctime < os.path.getctime(filepath): return False for (dirpath, dirnames, filenames) in os.walk('.'): for filename in filenames: if (fnmatch.fnmatch(filename, '*~') or not fnmatch.fnmatch(filename, 'Kconfig*') and not filename == 'MAINTAINERS'): continue filepath = os.path.join(dirpath, filename) if ctime < os.path.getctime(filepath): return False |
f6c8f38ec tools/genboardscf... |
91 |
# Detect a board that has been removed since the current board database |
d1bf4afda tools/genboardscf... |
92 |
# was generated |
f6c8f38ec tools/genboardscf... |
93 |
with open(output) as f: |
d1bf4afda tools/genboardscf... |
94 95 96 97 98 99 100 101 102 |
for line in f: if line[0] == '#' or line == ' ': continue defconfig = line.split()[6] + '_defconfig' if not os.path.exists(os.path.join(CONFIG_DIR, defconfig)): return False return True |
3c08e8b85 tools: add genboa... |
103 |
### classes ### |
f6c8f38ec tools/genboardscf... |
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 |
class KconfigScanner: """Kconfig scanner.""" ### constant variable only used in this class ### _SYMBOL_TABLE = { 'arch' : 'SYS_ARCH', 'cpu' : 'SYS_CPU', 'soc' : 'SYS_SOC', 'vendor' : 'SYS_VENDOR', 'board' : 'SYS_BOARD', 'config' : 'SYS_CONFIG_NAME', 'options' : 'SYS_EXTRA_OPTIONS' } def __init__(self): """Scan all the Kconfig files and create a Config object.""" # Define environment variables referenced from Kconfig os.environ['srctree'] = os.getcwd() os.environ['UBOOTVERSION'] = 'dummy' os.environ['KCONFIG_OBJDIR'] = '' self._conf = kconfiglib.Config() def __del__(self): """Delete a leftover temporary file before exit. The scan() method of this class creates a temporay file and deletes it on success. If scan() method throws an exception on the way, the temporary file might be left over. In that case, it should be deleted in this destructor. """ if hasattr(self, '_tmpfile') and self._tmpfile: try_remove(self._tmpfile) def scan(self, defconfig): """Load a defconfig file to obtain board parameters. Arguments: defconfig: path to the defconfig file to be processed Returns: A dictionary of board parameters. It has a form of: { 'arch': <arch_name>, 'cpu': <cpu_name>, 'soc': <soc_name>, 'vendor': <vendor_name>, 'board': <board_name>, 'target': <target_name>, 'config': <config_header_name>, 'options': <extra_options> } """ # strip special prefixes and save it in a temporary file fd, self._tmpfile = tempfile.mkstemp() with os.fdopen(fd, 'w') as f: for line in open(defconfig): colon = line.find(':CONFIG_') if colon == -1: f.write(line) else: f.write(line[colon + 1:]) self._conf.load_config(self._tmpfile) try_remove(self._tmpfile) self._tmpfile = None params = {} # Get the value of CONFIG_SYS_ARCH, CONFIG_SYS_CPU, ... etc. # Set '-' if the value is empty. for key, symbol in self._SYMBOL_TABLE.items(): value = self._conf.get_symbol(symbol).get_value() if value: params[key] = value else: params[key] = '-' defconfig = os.path.basename(defconfig) params['target'], match, rear = defconfig.partition('_defconfig') assert match and not rear, '%s : invalid defconfig' % defconfig # fix-up for aarch64 if params['arch'] == 'arm' and params['cpu'] == 'armv8': params['arch'] = 'aarch64' # fix-up options field. It should have the form: # <config name>[:comma separated config options] if params['options'] != '-': params['options'] = params['config'] + ':' + \ params['options'].replace(r'\"', '"') elif params['config'] != params['target']: params['options'] = params['config'] return params def scan_defconfigs_for_multiprocess(queue, defconfigs): """Scan defconfig files and queue their board parameters This function is intended to be passed to multiprocessing.Process() constructor. Arguments: queue: An instance of multiprocessing.Queue(). The resulting board parameters are written into it. defconfigs: A sequence of defconfig files to be scanned. """ kconf_scanner = KconfigScanner() for defconfig in defconfigs: queue.put(kconf_scanner.scan(defconfig)) def read_queues(queues, params_list): """Read the queues and append the data to the paramers list""" for q in queues: while not q.empty(): params_list.append(q.get()) def scan_defconfigs(jobs=1): """Collect board parameters for all defconfig files. This function invokes multiple processes for faster processing. Arguments: jobs: The number of jobs to run simultaneously """ all_defconfigs = [] for (dirpath, dirnames, filenames) in os.walk(CONFIG_DIR): for filename in fnmatch.filter(filenames, '*_defconfig'): if fnmatch.fnmatch(filename, '.*'): continue all_defconfigs.append(os.path.join(dirpath, filename)) total_boards = len(all_defconfigs) processes = [] queues = [] for i in range(jobs): defconfigs = all_defconfigs[total_boards * i / jobs : total_boards * (i + 1) / jobs] q = multiprocessing.Queue(maxsize=-1) p = multiprocessing.Process(target=scan_defconfigs_for_multiprocess, args=(q, defconfigs)) p.start() processes.append(p) queues.append(q) # The resulting data should be accumulated to this list params_list = [] # Data in the queues should be retrieved preriodically. # Otherwise, the queues would become full and subprocesses would get stuck. while any([p.is_alive() for p in processes]): read_queues(queues, params_list) # sleep for a while until the queues are filled time.sleep(SLEEP_TIME) # Joining subprocesses just in case # (All subprocesses should already have been finished) for p in processes: p.join() # retrieve leftover data read_queues(queues, params_list) return params_list |
3c08e8b85 tools: add genboa... |
269 270 271 272 273 274 275 276 277 278 |
class MaintainersDatabase: """The database of board status and maintainers.""" def __init__(self): """Create an empty database.""" self.database = {} def get_status(self, target): """Return the status of the given board. |
f6c8f38ec tools/genboardscf... |
279 280 281 |
The board status is generally either 'Active' or 'Orphan'. Display a warning message and return '-' if status information is not found. |
3c08e8b85 tools: add genboa... |
282 |
Returns: |
f6c8f38ec tools/genboardscf... |
283 |
'Active', 'Orphan' or '-'. |
3c08e8b85 tools: add genboa... |
284 |
""" |
b8828e8ff tools/genboardscf... |
285 286 287 |
if not target in self.database: print >> sys.stderr, "WARNING: no status info for '%s'" % target return '-' |
3c08e8b85 tools: add genboa... |
288 289 290 291 292 293 |
tmp = self.database[target][0] if tmp.startswith('Maintained'): return 'Active' elif tmp.startswith('Orphan'): return 'Orphan' else: |
b8828e8ff tools/genboardscf... |
294 295 296 |
print >> sys.stderr, ("WARNING: %s: unknown status for '%s'" % (tmp, target)) return '-' |
3c08e8b85 tools: add genboa... |
297 298 299 |
def get_maintainers(self, target): """Return the maintainers of the given board. |
f6c8f38ec tools/genboardscf... |
300 301 302 |
Returns: Maintainers of the board. If the board has two or more maintainers, they are separated with colons. |
3c08e8b85 tools: add genboa... |
303 |
""" |
b8828e8ff tools/genboardscf... |
304 305 306 |
if not target in self.database: print >> sys.stderr, "WARNING: no maintainers for '%s'" % target return '' |
3c08e8b85 tools: add genboa... |
307 308 309 |
return ':'.join(self.database[target][1]) def parse_file(self, file): |
f6c8f38ec tools/genboardscf... |
310 |
"""Parse a MAINTAINERS file. |
3c08e8b85 tools: add genboa... |
311 |
|
f6c8f38ec tools/genboardscf... |
312 313 |
Parse a MAINTAINERS file and accumulates board status and maintainers information. |
3c08e8b85 tools: add genboa... |
314 315 316 317 318 319 320 321 |
Arguments: file: MAINTAINERS file to be parsed """ targets = [] maintainers = [] status = '-' for line in open(file): |
5dff844d7 tools/genboardscf... |
322 323 324 |
# Check also commented maintainers if line[:3] == '#M:': line = line[1:] |
3c08e8b85 tools: add genboa... |
325 326 327 328 329 330 331 332 333 334 335 336 337 |
tag, rest = line[:2], line[2:].strip() if tag == 'M:': maintainers.append(rest) elif tag == 'F:': # expand wildcard and filter by 'configs/*_defconfig' for f in glob.glob(rest): front, match, rear = f.partition('configs/') if not front and match: front, match, rear = rear.rpartition('_defconfig') if match and not rear: targets.append(front) elif tag == 'S:': status = rest |
9c2d60c37 tools/genboardscf... |
338 339 |
elif line == ' ': |
3c08e8b85 tools: add genboa... |
340 341 342 343 344 345 346 347 |
for target in targets: self.database[target] = (status, maintainers) targets = [] maintainers = [] status = '-' if targets: for target in targets: self.database[target] = (status, maintainers) |
f6c8f38ec tools/genboardscf... |
348 349 |
def insert_maintainers_info(params_list): """Add Status and Maintainers information to the board parameters list. |
3c08e8b85 tools: add genboa... |
350 |
|
f6c8f38ec tools/genboardscf... |
351 352 |
Arguments: params_list: A list of the board parameters |
3c08e8b85 tools: add genboa... |
353 |
""" |
f6c8f38ec tools/genboardscf... |
354 355 356 357 |
database = MaintainersDatabase() for (dirpath, dirnames, filenames) in os.walk('.'): if 'MAINTAINERS' in filenames: database.parse_file(os.path.join(dirpath, 'MAINTAINERS')) |
3c08e8b85 tools: add genboa... |
358 |
|
f6c8f38ec tools/genboardscf... |
359 360 361 362 363 |
for i, params in enumerate(params_list): target = params['target'] params['status'] = database.get_status(target) params['maintainers'] = database.get_maintainers(target) params_list[i] = params |
3c08e8b85 tools: add genboa... |
364 |
|
f6c8f38ec tools/genboardscf... |
365 366 |
def format_and_output(params_list, output): """Write board parameters into a file. |
3c08e8b85 tools: add genboa... |
367 |
|
f6c8f38ec tools/genboardscf... |
368 369 |
Columnate the board parameters, sort lines alphabetically, and then write them to a file. |
3c08e8b85 tools: add genboa... |
370 |
|
f6c8f38ec tools/genboardscf... |
371 372 373 |
Arguments: params_list: The list of board parameters output: The path to the output file |
3c08e8b85 tools: add genboa... |
374 |
""" |
f6c8f38ec tools/genboardscf... |
375 376 |
FIELDS = ('status', 'arch', 'cpu', 'soc', 'vendor', 'board', 'target', 'options', 'maintainers') |
3c08e8b85 tools: add genboa... |
377 |
|
f6c8f38ec tools/genboardscf... |
378 379 380 381 382 |
# First, decide the width of each column max_length = dict([ (f, 0) for f in FIELDS]) for params in params_list: for f in FIELDS: max_length[f] = max(max_length[f], len(params[f])) |
3c08e8b85 tools: add genboa... |
383 |
|
f6c8f38ec tools/genboardscf... |
384 385 386 387 388 389 390 |
output_lines = [] for params in params_list: line = '' for f in FIELDS: # insert two spaces between fields like column -t would line += ' ' + params[f].ljust(max_length[f]) output_lines.append(line.strip()) |
3c08e8b85 tools: add genboa... |
391 |
|
f6c8f38ec tools/genboardscf... |
392 393 |
# ignore case when sorting output_lines.sort(key=str.lower) |
79d45d32b tools/genboardscf... |
394 |
|
f6c8f38ec tools/genboardscf... |
395 396 397 398 |
with open(output, 'w') as f: f.write(COMMENT_BLOCK + ' '.join(output_lines) + ' ') |
79d45d32b tools/genboardscf... |
399 |
|
f6c8f38ec tools/genboardscf... |
400 401 |
def gen_boards_cfg(output, jobs=1, force=False): """Generate a board database file. |
3c08e8b85 tools: add genboa... |
402 403 |
Arguments: |
f6c8f38ec tools/genboardscf... |
404 |
output: The name of the output file |
3c08e8b85 tools: add genboa... |
405 |
jobs: The number of jobs to run simultaneously |
f6c8f38ec tools/genboardscf... |
406 |
force: Force to generate the output even if it is new |
3c08e8b85 tools: add genboa... |
407 |
""" |
79d45d32b tools/genboardscf... |
408 |
check_top_directory() |
f6c8f38ec tools/genboardscf... |
409 410 411 |
if not force and output_is_new(output): print "%s is up to date. Nothing to do." % output |
d1bf4afda tools/genboardscf... |
412 |
sys.exit(0) |
f6c8f38ec tools/genboardscf... |
413 414 415 |
params_list = scan_defconfigs(jobs) insert_maintainers_info(params_list) format_and_output(params_list, output) |
3c08e8b85 tools: add genboa... |
416 417 |
def main(): |
f6c8f38ec tools/genboardscf... |
418 419 420 421 |
try: cpu_count = multiprocessing.cpu_count() except NotImplementedError: cpu_count = 1 |
3c08e8b85 tools: add genboa... |
422 423 |
parser = optparse.OptionParser() # Add options here |
d1bf4afda tools/genboardscf... |
424 425 |
parser.add_option('-f', '--force', action="store_true", default=False, help='regenerate the output even if it is new') |
f6c8f38ec tools/genboardscf... |
426 427 428 429 |
parser.add_option('-j', '--jobs', type='int', default=cpu_count, help='the number of jobs to run simultaneously') parser.add_option('-o', '--output', default=OUTPUT_FILE, help='output file [default=%s]' % OUTPUT_FILE) |
3c08e8b85 tools: add genboa... |
430 |
(options, args) = parser.parse_args() |
d1bf4afda tools/genboardscf... |
431 |
|
f6c8f38ec tools/genboardscf... |
432 |
gen_boards_cfg(options.output, jobs=options.jobs, force=options.force) |
3c08e8b85 tools: add genboa... |
433 434 435 |
if __name__ == '__main__': main() |