2 # Copyright 2020 The Pigweed Authors
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 # use this file except in compliance with the License. You may obtain a copy of
8 # https://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations under
15 """Generates a BUILD.gn for a Python package.
17 Pass the script a list of paths to the root directory of a Python package (where
20 Don't forget to add the pw_python_package to a top-level group, or it will not
21 be included in the build.
24 from datetime import datetime
25 from pathlib import Path
27 from typing import Iterable, List, NamedTuple
29 from pw_presubmit import git_repo
32 # Copyright {datetime.now().year} The Pigweed Authors
34 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
35 # use this file except in compliance with the License. You may obtain a copy of
38 # https://www.apache.org/licenses/LICENSE-2.0
40 # Unless required by applicable law or agreed to in writing, software
41 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
42 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
43 # License for the specific language governing permissions and limitations under
46 import("//build_overrides/pigweed.gni")
48 import("$dir_pw_build/python.gni")
52 class PackageFiles(NamedTuple):
59 def _find_package_files(root_dir: Path) -> PackageFiles:
60 files = git_repo.list_files(pathspecs=('*.py', '*.toml', '*.cfg'),
63 package_files = PackageFiles([], [], [], [])
66 if file.parent == root_dir:
67 if file.name == 'setup.py' or file.suffix != '.py':
68 package_files.setup.append(file)
69 elif file.stem.startswith('test_') or file.stem.endswith('_test'):
70 package_files.tests.append(file)
72 package_files.other.append(file)
74 package_files.sources.append(file)
79 def _gn_list(name: str, files: Iterable[Path], base: Path) -> Iterable[str]:
83 yield f' "{file.relative_to(base).as_posix()}",'
87 def generate_build_gn(root_dir: Path):
88 files = _find_package_files(root_dir)
92 yield 'pw_python_package("py") {'
94 yield from _gn_list('setup', files.setup, root_dir)
95 yield from _gn_list('sources', files.sources, root_dir)
96 yield from _gn_list('tests', files.tests, root_dir)
98 # Don't include the "other" files for now.
99 # yield from _gn_list('other', files.other, root_dir)
104 def main(paths: Iterable[Path]):
106 path.joinpath('BUILD.gn').write_text(
107 '\n'.join(generate_build_gn(path)) + '\n')
110 if __name__ == '__main__':
111 if len(sys.argv) > 1:
112 main(Path(p).resolve() for p in sys.argv[1:])
114 print(__file__, '', __doc__.strip(), sep='\n', file=sys.stderr)