import re
import os
import sys
import cffi
def load_hdr(ffi, hdr_path):
with open(hdr_path) as f:
hdr = f.read()
hdr = re.sub("^#.*$", "", hdr, flags=re.MULTILINE)
hdr = re.sub(r"__CBINDGEN_ALIGNED\(\d+\)([^{;]*){([^}]+)}", r"\1 {\2 ...;}", hdr, flags=re.MULTILINE)
ffi.cdef(hdr)
def compile_module(**kwargs):
ffibuilder = cffi.FFI()
ffibuilder.cdef("typedef uint32_t dev_t;")
for include_dir in kwargs["include_dirs"]:
pathrs_hdr = os.path.join(include_dir, "pathrs.h")
if os.path.exists(pathrs_hdr):
load_hdr(ffibuilder, pathrs_hdr)
ffibuilder.set_source("_pathrs", "#include <pathrs.h>",
libraries=["pathrs"], **kwargs)
ffibuilder.compile(verbose=True)
def main():
ROOT_DIR = None
candidate = os.path.dirname(sys.path[0] or os.getcwd())
while candidate != "/":
try:
candidate_toml = os.path.join(candidate, "Cargo.toml")
with open(candidate_toml, "r") as f:
content = f.read()
if re.findall(r'^name = "pathrs"$', content, re.MULTILINE):
ROOT_DIR = candidate
break
except:
pass
candidate = os.path.dirname(candidate)
if not ROOT_DIR:
raise RuntimeError("Could not find pathrs source-dir root.")
lib_paths = []
for mode in ["debug", "release"]:
so_path = os.path.join(ROOT_DIR, "target/%s/libpathrs.so" % (mode,))
if os.path.exists(so_path):
lib_paths.append(so_path)
lib_paths = sorted(lib_paths, key=lambda path: -os.path.getmtime(path))
lib_paths = [os.path.dirname(path) for path in lib_paths]
compile_module(include_dirs=[os.path.join(ROOT_DIR, "include")],
library_dirs=lib_paths)
if __name__ == "__main__":
main()