xref: /openbmc/sdbusplus/tools/sdbus++-gen-meson (revision 1caa5e8a)
1#!/usr/bin/env bash
2
3set -e
4
5# Locale can change behavior of utilities like 'sort' but we want the output
6# to be stable on all machines.  Force the locale to 'C' for consistency.
7export LC_ALL=C
8
9function show_usage() {
10    cat \
11        << EOF
12Usage: $(basename "$0") [options] <command-args>*
13
14Generate meson.build files from a directory tree containing YAML files and
15facilitate building the sdbus++ sources.
16
17Options:
18    --help              - Display this message
19    --command <cmd>     - Command mode to execute (default 'meson').
20    --directory <path>  - Root directory of the YAML source (default '.').
21    --output <path>     - Root directory of the output (default '.').
22    --tool <path>       - Path to the processing tool (default 'sdbus++').
23    --version           - Display this tool's version string.
24
25Commands:
26    meson               - Generate a tree of meson.build files corresponding
27                          to the source YAML files.
28    cpp <intf>          - Generate the source files from a YAML interface.
29    markdown <intf>     - Generate the markdown files from a YAML interface.
30    version             - Display this tool's version string.
31
32EOF
33}
34
35## The version is somewhat arbitrary but is used to create a warning message
36## if a repository contains old copies of the generated meson.build files and
37## needs an update.  We should increment the version number whenever the
38## resulting meson.build would change.
39tool_version="sdbus++-gen-meson version 6"
40function show_version() {
41    echo "${tool_version}"
42}
43
44# Set up defaults.
45sdbuspp="sdbus++"
46outputdir="."
47cmd="meson"
48rootdir="."
49
50# Parse options.
51options="$(getopt -o hc:d:o:t:v --long help,command:,directory:,output:,tool:,version -- "$@")"
52eval set -- "${options}"
53
54while true; do
55    case "$1" in
56        -h | --help)
57            show_usage
58            exit
59            ;;
60
61        -c | --command)
62            shift
63            cmd="$1"
64            shift
65            ;;
66
67        -d | --directory)
68            shift
69            rootdir="$1"
70            shift
71            ;;
72
73        -o | --output)
74            shift
75            outputdir="$1"
76            shift
77            ;;
78
79        -t | --tool)
80            shift
81            sdbuspp="$1"
82            shift
83            ;;
84
85        -v | --version)
86            show_version
87            exit
88            ;;
89
90        --)
91            shift
92            break
93            ;;
94
95        *)
96            echo "Invalid argument $1"
97            exit 1
98            ;;
99    esac
100done
101
102## Create an initially empty meson.build file.
103## $1 - path to create meson.build at.
104function meson_empty_file() {
105    mkdir -p "$1"
106    echo "# Generated file; do not modify." > "$1/meson.build"
107}
108
109## Create the root-level meson.build
110##
111## Inserts rules to run the available version of this tool to ensure the
112## version has not changed.
113function meson_create_root() {
114    meson_empty_file "${outputdir}"
115
116    cat >> "${outputdir}/meson.build" \
117        << EOF
118sdbuspp_gen_meson_ver = run_command(
119    sdbuspp_gen_meson_prog,
120    '--version',
121    check: true,
122).stdout().strip().split('\n')[0]
123
124if sdbuspp_gen_meson_ver != '${tool_version}'
125    warning('Generated meson files from wrong version of sdbus++-gen-meson.')
126    warning(
127        'Expected "${tool_version}", got:',
128        sdbuspp_gen_meson_ver
129    )
130endif
131
132EOF
133}
134
135## hash-tables to store:
136##      meson_paths - list of subdirectory paths for which an empty meson.build
137##                    has already been created.
138##      interfaces - list of interface paths which a YAML has been found and
139##                   which YAML types (interface, errors, etc.).
140declare -A meson_paths
141declare -A interfaces
142
143## Ensure the meson.build files to a path have been created.
144## $1 - The path requiring to be created.
145function meson_create_path() {
146
147    meson_path="${outputdir}"
148    prev_meson_path=""
149
150    # Split the path into segments.
151    for part in $(echo "$1" | tr '/' '\n'); do
152        prev_meson_path="${meson_path}"
153        meson_path="${meson_path}/${part}"
154
155        # Create the meson.build for this segment if it doesn't already exist.
156        if [[ "" == "${meson_paths[${meson_path}]}" ]]; then
157            meson_paths["${meson_path}"]="1"
158            meson_empty_file "${meson_path}"
159
160            # Add the 'subdir' link into the parent's meson.build.
161            # We need to skip adding the links into the 'root' meson.build
162            # because most repositories want to selectively add TLDs based
163            # on config flags.  Let them figure out their own logic for that.
164            if [[ ${outputdir} != "${prev_meson_path}" ]]; then
165                echo "subdir('${part}')" >> "${prev_meson_path}/meson.build"
166            fi
167        fi
168    done
169}
170
171## Generate the meson target for the source files (.cpp/.hpp) from a YAML
172## interface.
173##
174## $1 - The interface to generate a target for.
175function meson_cpp_target() {
176    mesondir="${outputdir}/$1"
177    yamldir="$(realpath --relative-to="${mesondir}" "${rootdir}")"
178
179    # Determine the source and output files based on the YAMLs present.
180    sources=""
181    outputs=""
182    for s in ${interfaces[$1]}; do
183        sources="'${yamldir}/$1.${s}', "
184
185        case "${s}" in
186            errors.yaml)
187                outputs="${outputs}'error.cpp', 'error.hpp', "
188                ;;
189
190            interface.yaml)
191                outputs="${outputs}'common.hpp', "
192                outputs="${outputs}'server.cpp', 'server.hpp', "
193                outputs="${outputs}'client.hpp', "
194                ;;
195
196            *)
197                echo "Unknown interface type: ${s}"
198                exit 1
199                ;;
200        esac
201    done
202
203    # Create the target to generate the 'outputs'.
204    cat >> "${mesondir}/meson.build" \
205        << EOF
206generated_sources += custom_target(
207    '$1__cpp'.underscorify(),
208    input: [ ${sources} ],
209    output: [ ${outputs} ],
210    depend_files: sdbusplusplus_depfiles,
211    command: [
212        sdbuspp_gen_meson_prog, '--command', 'cpp',
213        '--output', meson.current_build_dir(),
214        '--tool', sdbusplusplus_prog,
215        '--directory', meson.current_source_dir() / '${yamldir}',
216        '$1',
217    ],
218)
219
220EOF
221}
222
223## Generate the meson target for the markdown files from a YAML interface.
224## $1 - The interface to generate a target for.
225function meson_md_target() {
226    mesondir="${outputdir}/$(dirname "$1")"
227    yamldir="$(realpath --relative-to="${mesondir}" "${rootdir}")"
228
229    # Determine the source files based on the YAMLs present.
230    sources=""
231    for s in ${interfaces[$1]}; do
232        sources="'${yamldir}/$1.${s}', "
233    done
234
235    # Create the target to generate the interface.md file.
236    cat >> "${mesondir}/meson.build" \
237        << EOF
238generated_others += custom_target(
239    '$1__markdown'.underscorify(),
240    input: [ ${sources} ],
241    output: [ '$(basename "$1").md' ],
242    depend_files: sdbusplusplus_depfiles,
243    command: [
244        sdbuspp_gen_meson_prog, '--command', 'markdown',
245        '--output', meson.current_build_dir(),
246        '--tool', sdbusplusplus_prog,
247        '--directory', meson.current_source_dir() / '${yamldir}',
248        '$1',
249    ],
250)
251
252EOF
253}
254
255## Handle command=meson by generating the tree of meson.build files.
256function cmd_meson() {
257    # Find and sort all the YAML files
258    yamls="$(find "${rootdir}" -name '*.interface.yaml' -o -name '*.errors.yaml')"
259    yamls="$(echo "${yamls}" | sort)"
260
261    # Assign the YAML files into the hash-table by interface name.
262    for y in ${yamls}; do
263        rel="$(realpath "--relative-to=${rootdir}" "${y}")"
264        dir="$(dirname "${rel}")"
265        ext="${rel#*.}"
266        base="$(basename "${rel}" ".${ext}")"
267        key="${dir}/${base}"
268
269        interfaces["${key}"]="${interfaces[${key}]} ${ext}"
270    done
271
272    # Create the meson.build files.
273    meson_create_root
274    # shellcheck disable=SC2312
275    sorted_ifaces="$(echo "${!interfaces[@]}" | tr " " "\n" | sort)"
276    for i in ${sorted_ifaces}; do
277        meson_create_path "${i}"
278        meson_cpp_target "${i}"
279        meson_md_target "${i}"
280    done
281}
282
283## Handle command=cpp by calling sdbus++ as appropriate.
284## $1 - interface to generate.
285##
286## For an interface foo/bar, the outputdir is expected to be foo/bar.
287function cmd_cpp() {
288
289    if [[ "" == "$1" ]]; then
290        show_usage
291        exit 1
292    fi
293
294    if [[ ! -e "${rootdir}/$1.interface.yaml" ]] &&
295    [[ ! -e "${rootdir}/$1.errors.yaml" ]]; then
296        echo "Missing YAML for $1."
297        exit 1
298    fi
299
300    mkdir -p "${outputdir}"
301
302    sdbusppcmd="${sdbuspp} -r ${rootdir}"
303    intf="${1//\//.}"
304
305    if [[ -e "${rootdir}/$1.interface.yaml" ]]; then
306        ${sdbusppcmd} interface common-header "${intf}" > "${outputdir}/common.hpp"
307        ${sdbusppcmd} interface server-header "${intf}" > "${outputdir}/server.hpp"
308        ${sdbusppcmd} interface server-cpp "${intf}" > "${outputdir}/server.cpp"
309        ${sdbusppcmd} interface client-header "${intf}" > "${outputdir}/client.hpp"
310    fi
311
312    if [[ -e "${rootdir}/$1.errors.yaml" ]]; then
313        ${sdbusppcmd} error exception-header "${intf}" > "${outputdir}/error.hpp"
314        ${sdbusppcmd} error exception-cpp "${intf}" > "${outputdir}/error.cpp"
315    fi
316}
317
318## Handle command=markdown by calling sdbus++ as appropriate.
319## $1 - interface to generate.
320##
321## For an interface foo/bar, the outputdir is expected to be foo.
322function cmd_markdown() {
323
324    if [[ "" == "$1" ]]; then
325        show_usage
326        exit 1
327    fi
328
329    if [[ ! -e "${rootdir}/$1.interface.yaml" ]] &&
330    [[ ! -e "${rootdir}/$1.errors.yaml" ]]; then
331        echo "Missing YAML for $1."
332        exit 1
333    fi
334
335    mkdir -p "${outputdir}"
336
337    sdbusppcmd="${sdbuspp} -r ${rootdir}"
338    intf="${1//\//.}"
339    base="$(basename "$1")"
340
341    echo -n > "${outputdir}/${base}.md"
342    if [[ -e "${rootdir}/$1.interface.yaml" ]]; then
343        ${sdbusppcmd} interface markdown "${intf}" >> "${outputdir}/${base}.md"
344    fi
345
346    if [[ -e "${rootdir}/$1.errors.yaml" ]]; then
347        ${sdbusppcmd} error markdown "${intf}" >> "${outputdir}/${base}.md"
348    fi
349}
350
351## Handle command=version.
352function cmd_version() {
353    show_version
354}
355
356"cmd_${cmd}" "$*"
357