xref: /aosp_15_r20/external/flatbuffers/scripts/util.py (revision 890232f25432b36107d06881e0a25aaa6b473652)
1# Copyright 2022 Google Inc. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import platform
16import subprocess
17from pathlib import Path
18
19# Get the path where this script is located so we can invoke the script from
20# any directory and have the paths work correctly.
21script_path = Path(__file__).parent.resolve()
22
23# Get the root path as an absolute path, so all derived paths are absolute.
24root_path = script_path.parent.absolute()
25
26# Get the location of the flatc executable, reading from the first command line
27# argument or defaulting to default names.
28flatc_exe = Path("flatc" if not platform.system() == "Windows" else "flatc.exe")
29
30# Find and assert flatc compiler is present.
31if root_path in flatc_exe.parents:
32    flatc_exe = flatc_exe.relative_to(root_path)
33flatc_path = Path(root_path, flatc_exe)
34assert flatc_path.exists(), "Cannot find the flatc compiler " + str(flatc_path)
35
36# Execute the flatc compiler with the specified parameters
37def flatc(options, schema, prefix=None, include=None, data=None, cwd=root_path):
38    cmd = [str(flatc_path)] + options
39    if prefix:
40        cmd += ["-o"] + [prefix]
41    if include:
42        cmd += ["-I"] + [include]
43    if isinstance(schema, Path):
44      cmd += [str(schema)]
45    elif isinstance(schema, str):
46      cmd += [schema]
47    else:
48      cmd += schema
49    if data:
50        cmd += [data] if isinstance(data, str) else data
51    return subprocess.check_call(cmd, cwd=str(cwd))
52