Skip to content
Snippets Groups Projects
__init__.py 1.64 KiB
Newer Older
# Version of the Namespace package "dummy"
__version__ = "2021.01.a1"

# contains also script to auto-compile .proto files into python classes
# https://stackoverflow.com/questions/23585450/automate-compilation-of-protobuf-specs-into-python-classes-in-setup-py
import os, sys, subprocess
from pathlib import Path
from distutils.spawn import find_executable

# find protoc installation
# TODO note somewhere that protobuf-compiler needed to compile them
if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
  protoc = os.environ['PROTOC']
else:
  protoc = find_executable('protoc')

# search all proto files in this package
this_dir = os.path.dirname(os.path.realpath(__file__)) # this dir
working_dir = os.path.join(this_dir, 'identification')
proto_files_g = list(Path(working_dir).rglob("*.[pP][rR][oO][tT][oO]"))
python_out = os.path.join(working_dir, '_proto_gen')

# create pb2 and put them in the correct directory
for path in proto_files_g:
    path_dir = os.path.dirname(path)
    output_file = os.path.join(python_out, os.path.basename(path).split('.')[0] + '_pb2.py')

    # generate if source file newer or output file non existent
    if not os.path.exists(output_file) or (os.path.getmtime(path) > os.path.getmtime(output_file)):
        if protoc is None:
            print("Protoc recompilation needed, but no proto-compiler found. Install it, e.g. protobuf-compiler via apt.")
            sys.exit(1)
        protoc_command = [protoc, '-I=' + path_dir, '--proto_path=' + working_dir, '--python_out=' + python_out, path]
        print("Execute protoc for: " + str(path))
        if subprocess.call(protoc_command) != 0:
            sys.exit(1)