Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
# Copyright (c) 2026 TiaC Systems
# Copyright (c) 2020 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: Apache-2.0
import os
import re
from pathlib import Path
import yaml
from docutils import io, statemachine
from docutils.parsers.rst import directives
from sphinx.util.docutils import SphinxDirective
__version__ = '0.1.0'
class TableFromRows(SphinxDirective):
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {
'header': directives.unchanged,
'rows': directives.unchanged,
}
def _load_section(self, lines, section):
found_section = False
section_lines = []
for line in lines:
line = line.strip()
if line == '.. ' + section:
found_section = True
continue
elif line.startswith('.. ') and found_section:
break
if found_section and line != '':
section_lines.append(line)
if len(section_lines) == 0:
raise self.severe(f'Problems building table; "{section}" section not found.')
return section_lines
def _column_sizes(self, row):
cols = row.split('|')
if len(cols) < 2 or cols[0] != '' or cols[-1] != '':
raise self.severe(f'Row does not look like a table: "{row}"')
return [len(el.strip()) for el in cols[1:-1]]
@staticmethod
def _adjust_column_sizes(sizes, line):
columns = []
for size, column in zip(sizes, line.split('|')[1:-1], strict=False):
column = column.strip()
columns.append(column + ' ' * (size - len(column)))
return '|' + '|'.join(columns) + '|'
def _build_table(self, sizes, header_lines, rows):
row_sep = '+' + '+'.join(['-' * size for size in sizes]) + '+'
table = [row_sep]
# XXX for header_lines to be len==1?
for line in header_lines:
table.append(self._adjust_column_sizes(sizes, line))
table.append('+' + '+'.join(['=' * size for size in sizes]) + '+')
for row_set in rows:
for line in row_set:
table.append(self._adjust_column_sizes(sizes, line))
table.append(row_sep)
return table
def _find_column_sizes(self, header_lines, rows):
sizes = self._column_sizes(header_lines[0])
for row in header_lines[1:]:
row_sizes = self._column_sizes(row)
if len(sizes) != len(row_sizes):
raise self.severe(f'Incompatible number of columns: "{row}"')
sizes = [max(sizes[i], row_sizes[i]) for i, _ in enumerate(sizes)]
for row_set in rows:
for row in row_set:
row_sizes = self._column_sizes(row)
if len(sizes) != len(row_sizes):
raise self.severe(f'Incompatible number of columns: "{row}"')
sizes = [max(sizes[i], row_sizes[i]) for i, _ in enumerate(sizes)]
return sizes
def _load_header_and_rows(
self,
source_path,
header_section,
rows_sections,
transform_rows_func=None,
shields=None,
):
try:
self.state.document.settings.record_dependencies.add(source_path)
include_file = io.FileInput(source_path=source_path)
except OSError as error:
raise self.severe(
f'Problems with "{self.name}" directive path:\n{io.error_string(error)}.'
) from error
lines = include_file.readlines()
header_lines = self._load_section(lines, header_section)
rows = [self._load_section(lines, section) for section in rows_sections]
if shields:
header_lines[0] += ' Shields |'
for i, target in enumerate(rows_sections):
target = target.replace("_", "/")
if target in shields:
rows[i][0] += f'``{"`` ``".join(shields[target])}``'
rows[i][0] += ' |'
if transform_rows_func:
transform_rows_func(rows)
column_sizes = self._find_column_sizes(header_lines, rows)
return self._build_table(column_sizes, header_lines, rows)
def run(self):
_, path = self.env.relfn2path(self.arguments[0])
header = self.options.get('header', None)
if header is not None:
header = header.strip()
else:
raise self.severe(
f'Problem with "header" option of "{self.name}" ' 'directive:\nEmpty content.'
)
rows = self.options.get('rows', None)
if rows is not None:
rows = [r.strip() for r in rows.split(',') if r.strip() != '']
else:
raise self.severe(f'No "rows" content provided for "{self.name}" ')
# join all rows for uniqueness, using the order given in
# the :rows: option.
all_rows = {}
all_rows.update(dict.fromkeys(rows))
raw = '\n'.join(self._load_header_and_rows(path, header, all_rows.keys()))
lines = statemachine.string2lines(raw)
self.state_machine.insert_input(lines, path)
return []
class TableFromTestsYaml(TableFromRows):
option_spec = {}
required_arguments = 0
@staticmethod
def _merge_rows(rows):
"""Merge rows where all columns except the build target are equal."""
seen = {}
to_delete = []
for row in rows:
columns = row[0].split('|')[1:-1]
common_info = '|'.join(columns[:3]) + '|' + '|'.join(columns[4:])
build_target = columns[3]
if common_info in seen:
extended_row = f'| | | | {build_target} |' + ' |' * len(columns[4:])
seen[common_info].append(extended_row)
to_delete.append(row)
else:
seen[common_info] = row
for row in to_delete:
rows.remove(row)
@staticmethod
def _normalize_boards(boards: list[str]) -> list[str]:
return [board.replace("/", "_") for board in boards]
@staticmethod
def _find_shields(shields: dict[str, set[str]], tests_data: dict):
"""Associate all integration platforms for tests with any shield used."""
extra_args_raw = tests_data.get('extra_args')
if not extra_args_raw:
return
if isinstance(extra_args_raw, str):
extra_args = extra_args_raw.split()
else:
extra_args = extra_args_raw
shield_args = [re.split(r'=', arg)[1] for arg in extra_args if 'SHIELD=' in arg]
if not shield_args:
return
for platform in tests_data['integration_platforms']:
if platform in shields:
shields[platform].update(shield_args)
else:
shields[platform] = set(shield_args)
def _rows_from_tests_yaml(self, path):
"""Search for a tests.yaml file and return a union of all relevant boards.
Boards are retrieved from the integration_platforms sections in the file.
If the file is not found and the document folder is named "doc", the
parent folder is searched. Should a tests.yaml still not be found, all
subfolders are searched and every found tests.yaml is used.
Shields are retrieved from the extra_args sections in the file for every
argument prefixed with "SHIELD=".
nrf51 and qemu boards are ignored."""
# Path from rst-file in build folder to source build directory.
rel_path = os.path.relpath(path, self.env.srcdir)
# In cases where ``path`` for some reason is not pointing to the
# build folder, remove all instances of '../' from the path.
rel_path = rel_path.lstrip('..' + os.path.sep)
# Path to the origin of the rst-file outside the build folder
dir_path = Path(self.config.table_from_rows_base_dir) / rel_path
tests_yamls = []
if (dir_path / 'tests.yaml').exists():
tests_yamls.append(dir_path / 'tests.yaml')
elif rel_path.endswith('doc'):
parent_path = dir_path.parent / 'tests.yaml'
if parent_path.exists():
tests_yamls.append(parent_path)
else:
tests_yamls += list(dir_path.glob('**/tests.yaml'))
if not tests_yamls:
raise self.severe(f'"{path}" not found')
boards = set()
shields = {}
for tests_yaml_path in tests_yamls:
with open(tests_yaml_path) as tests_yaml:
data = yaml.safe_load(tests_yaml)
if 'common' in data and 'integration_platforms' in data['common']:
boards.update(
TableFromTestsYaml._normalize_boards(data['common']['integration_platforms'])
)
self._find_shields(shields, data['common'])
for test in data['tests'].values():
if 'integration_platforms' in test:
boards.update(
TableFromTestsYaml._normalize_boards(test['integration_platforms'])
)
self._find_shields(shields, test)
boards = list(
filter(
lambda b: not b.startswith('qemu') and not b.startswith('nrf51'),
boards,
)
)
boards.sort(reverse=True)
if not boards:
raise self.severe(f'{path} has no relevant integration_platforms')
return boards, shields
def run(self):
reference_file = self.config.table_from_tests_yaml_board_reference
_, path = self.env.relfn2path(reference_file)
source = self.state_machine.input_lines.source(
self.lineno - self.state_machine.input_offset - 1
)
source_dir = os.path.dirname(os.path.abspath(source))
tests_yaml_rows, shields = self._rows_from_tests_yaml(source_dir)
raw = '\n'.join(
self._load_header_and_rows(
path,
'heading',
tests_yaml_rows,
transform_rows_func=self._merge_rows,
shields=shields,
)
)
lines = statemachine.string2lines(raw)
self.state_machine.insert_input(lines, path)
return []
def setup(app):
app.add_config_value('table_from_rows_base_dir', None, 'env')
app.add_config_value('table_from_tests_yaml_board_reference', None, 'env')
directives.register_directive('table-from-rows', TableFromRows)
directives.register_directive('table-from-tests-yaml', TableFromTestsYaml)
return {
'version': __version__,
'parallel_read_safe': True,
'parallel_write_safe': True,
}
55022eb50This file is pinned to the selected release. Download the original to open it in your design tool.