1#!/usr/bin/env python3 2# Copyright (c) Meta Platforms, Inc. and affiliates. 3# All rights reserved. 4# 5# This source code is licensed under the BSD-style license found in the 6# LICENSE file in the root directory of this source tree. 7 8import json 9import os 10import shutil 11import subprocess 12 13 14def calculate_project_name(path_to_root): 15 """ 16 Get a cmake project name for that path using relative path. 17 >>> calculate_project_name("runtime/core/portable_type/test") 18 'runtime_core_portable_type_test' 19 """ 20 return path_to_root.replace("/", "_") 21 22 23def calculate_relative_path(path_to_root): 24 """ 25 Return the relative path from the path_to_root to root (i.e. "..") 26 >>> calculate_relative_path("runtime/core/portable_type/test") 27 '../../../..' 28 """ 29 return os.path.relpath("/", "/" + path_to_root) 30 31 32def format_template(path_to_root, test_srcs, additional_libs): 33 """ 34 Format the template with the given path_to_root and test_srcs. 35 """ 36 with open(os.path.dirname(os.path.abspath(__file__)) + "/OSSTest.cmake.in") as f: 37 template = f.read() 38 return template.format( 39 project_name=calculate_project_name(path_to_root), 40 path_to_root=calculate_relative_path(path_to_root), 41 test_srcs=" ".join(test_srcs), 42 additional_libs=" ".join(additional_libs), 43 ) 44 45 46def write_template(path_to_root, test_srcs, additional_libs): 47 """ 48 Write the template to the given path_to_root. 49 """ 50 with open(os.path.join(path_to_root, "CMakeLists.txt"), "w") as f: 51 f.write(format_template(path_to_root, test_srcs, additional_libs)) 52 53 54def read_config_json(json_path): 55 """ 56 Read the config.json file 57 """ 58 with open(json_path) as f: 59 config = json.load(f) 60 return config["tests"] 61 62 63if __name__ == "__main__": 64 json_path = os.path.dirname(os.path.abspath(__file__)) + "/OSSTestConfig.json" 65 for d in read_config_json(json_path): 66 path_to_root = d["directory"] 67 test_srcs = d["sources"] 68 additional_libs = d.get("additional_libs", []) 69 write_template(path_to_root, test_srcs, additional_libs) 70 if shutil.which("cmake-format") is not None: 71 subprocess.run( 72 ["cmake-format", "-i", path_to_root + "/CMakeLists.txt"], check=True 73 ) 74 else: 75 print(f"Please run cmake-format -i {path_to_root}/CMakeLists.txt") 76