1"""Build rules to generate metadata schema versions."""
2
3METADATA_SCHEMA_FILE = "//tensorflow_lite_support/metadata:metadata_schema.fbs"
4
5def stamp_metadata_parser_version(
6        name,
7        srcs,
8        outs):
9    """Stamps the latest metadata parser version into the srcs files.
10
11    Replaces all the occurrences of "{LATEST_METADATA_PARSER_VERSION}" in the
12    srcs files with the metadata schema version extracted from
13    METADATA_SCHEMA_FILE and then outputs the generated file into outs,
14    respectively. The number of srcs files needs to match the number of outs
15    files.
16
17    Args:
18        name: Rule name. (required)
19        srcs: List of source files. (required)
20        outs: List of output files. (required)
21    """
22    if len(srcs) != len(outs):
23        fail(("The number of srcs files (%d) does not match that of the outs" +
24              " files (%d).") %
25             (len(srcs), len(outs)))
26
27    for i in range(0, len(srcs)):
28        native.genrule(
29            name = "%s_file%d" % (name, i),
30            srcs = [srcs[i]],
31            outs = [outs[i]],
32            tools = [METADATA_SCHEMA_FILE],
33            # Gets the metadata schema version from the file, and stamps it
34            # into the srcs file.
35            cmd = "version=$$(sed -n -e '/Schema Semantic version/ s/.*\\: *//p' $(location %s));" %
36                  METADATA_SCHEMA_FILE +
37                  'sed "s/{LATEST_METADATA_PARSER_VERSION}/$$version/" $< > $@',
38        )
39
40    native.filegroup(
41        name = name,
42        srcs = outs,
43    )
44