zephyr/cmake/yaml-filter.cmake
Luca Burelli cdc7f05cc9 cmake: yaml: add support for generator expressions
This commit adds support for generator expressions in values and lists
to the yaml module.

Generator expressions can only be expanded by CMake after all
configuration code has been executed and the final values of the project
properties are defined. This means that contexts that contain generator
expressions are written twice:

 - immediately, during the 'yaml_save()' call, a comment with the raw
   unexpanded string is saved instead of the key that uses generator
   expressions in the YAML file;

 - after the configuration step, a custom command updates the YAML file
   contents with the fully expanded values.

This two-step process also allows to overcome the issue of lists that
are extracted from generator expressions, whose elements would be
expanded into a single string if written directly to the YAML file.
Instead, the lists are stored in their CMake string format with a
special marker, expanded by CMake into a temporary JSON file, and the
conversion to a proper list is performed during the build step.

If the saved YAML file for context <name> is needed by further build
steps in this project, the target '<name>_yaml_saved' must be added as a
dependency to ensure the final contents are ready.

Note that when generator expressions are used in the context, the GENEX
keyword must be provided to yaml_set(). This is necessary to avoid
storing the genexes as raw strings in the YAML.

Signed-off-by: Luca Burelli <l.burelli@arduino.cc>
2025-01-30 14:10:53 +01:00

36 lines
1.3 KiB
CMake

# Copyright (c) 2024 Arduino SA
# SPDX-License-Identifier: Apache-2.0
# Simple second stage filter for YAML generation, used when generator
# expressions have been used for some of the data and the conversion to
# YAML needs to happen after cmake has completed processing.
#
# This scripts expects as input:
# - JSON_FILE: the name of the input file, in JSON format, that contains
# the expanded generator expressions.
# - YAML_FILE: the name of the final output YAML file.
# - TEMP_FILES: a list of temporary files that need to be removed after
# the conversion is done.
#
# This script loads the Zephyr yaml module and reuses its `to_yaml()`
# function to convert the fully expanded JSON content to YAML, taking
# into account the special format that was used to store lists.
# Temporary files are then removed.
cmake_minimum_required(VERSION 3.20.0)
set(ZEPHYR_BASE ${CMAKE_CURRENT_LIST_DIR}/../)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/modules")
include(yaml)
file(READ ${JSON_FILE} json_content)
to_yaml("${json_content}" 0 yaml_out TRUE)
file(WRITE ${YAML_FILE} "${yaml_out}")
# Remove unused temporary files. JSON_FILE needs to be kept, or the
# build system will complain there is no rule to rebuild it
list(REMOVE_ITEM TEMP_FILES ${JSON_FILE})
foreach(file ${TEMP_FILES})
file(REMOVE ${file})
endforeach()