• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://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, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Generates nanopb_pb2.py by importing the Nanopb proto module.
15
16The Nanopb repository generates nanopb_pb2.py dynamically when its Python
17package is imported if it does not exist. If multiple processes try to use
18Nanopb to compile simultaneously on a clean build, they can interfere with each
19other. One process might rewrite nanopb_pb2.py as another process is trying to
20access it, resulting in import errors.
21
22This script imports the Nanopb module so that nanopb_pb2.py is generated if it
23doesn't exist. All Nanopb proto compilation targets depend on this script so
24that nanopb_pb2.py is guaranteed to exist before they need it.
25"""
26
27import argparse
28import importlib.util
29from pathlib import Path
30import sys
31
32
33def generate_nanopb_proto(root: Path) -> None:
34    sys.path.append(str(root / 'generator'))
35
36    spec = importlib.util.spec_from_file_location(
37        'proto', root / 'generator' / 'proto' / '__init__.py'
38    )
39    assert spec is not None
40    proto_module = importlib.util.module_from_spec(spec)
41    spec.loader.exec_module(proto_module)  # type: ignore[union-attr]
42
43
44def _parse_args() -> argparse.Namespace:
45    parser = argparse.ArgumentParser(description=__doc__)
46    parser.add_argument('root', type=Path, help='Nanopb root')
47    return parser.parse_args()
48
49
50if __name__ == '__main__':
51    generate_nanopb_proto(**vars(_parse_args()))
52