pytorch
85 строк · 2.8 Кб
1"""
2This is refactored from cmake.py to avoid circular imports issue with env.py,
3which calls get_cmake_cache_variables_from_file
4"""
5
6from __future__ import annotations7
8import re9from typing import IO, Optional, Union10
11
12CMakeValue = Optional[Union[bool, str]]13
14
15def convert_cmake_value_to_python_value(16cmake_value: str, cmake_type: str17) -> CMakeValue:18r"""Convert a CMake value in a string form to a Python value.19
20Args:
21cmake_value (string): The CMake value in a string form (e.g., "ON", "OFF", "1").
22cmake_type (string): The CMake type of :attr:`cmake_value`.
23
24Returns:
25A Python value corresponding to :attr:`cmake_value` with type :attr:`cmake_type`.
26"""
27
28cmake_type = cmake_type.upper()29up_val = cmake_value.upper()30if cmake_type == "BOOL":31# https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/VariablesListsStrings#boolean-values-in-cmake32return not (33up_val in ("FALSE", "OFF", "N", "NO", "0", "", "NOTFOUND")34or up_val.endswith("-NOTFOUND")35)36elif cmake_type == "FILEPATH":37if up_val.endswith("-NOTFOUND"):38return None39else:40return cmake_value41else: # Directly return the cmake_value.42return cmake_value43
44
45def get_cmake_cache_variables_from_file(46cmake_cache_file: IO[str],47) -> dict[str, CMakeValue]:48r"""Gets values in CMakeCache.txt into a dictionary.49
50Args:
51cmake_cache_file: A CMakeCache.txt file object.
52Returns:
53dict: A ``dict`` containing the value of cached CMake variables.
54"""
55
56results = {}57for i, line in enumerate(cmake_cache_file, 1):58line = line.strip()59if not line or line.startswith(("#", "//")):60# Blank or comment line, skip61continue62
63# Almost any character can be part of variable name and value. As a practical matter, we assume the type must be64# valid if it were a C variable name. It should match the following kinds of strings:65#66# USE_CUDA:BOOL=ON67# "USE_CUDA":BOOL=ON68# USE_CUDA=ON69# USE_CUDA:=ON70# Intel(R) MKL-DNN_SOURCE_DIR:STATIC=/path/to/pytorch/third_party/ideep/mkl-dnn71# "OpenMP_COMPILE_RESULT_CXX_openmp:experimental":INTERNAL=FALSE72matched = re.match(73r'("?)(.+?)\1(?::\s*([a-zA-Z_-][a-zA-Z0-9_-]*)?)?\s*=\s*(.*)', line74)75if matched is None: # Illegal line76raise ValueError(f"Unexpected line {i} in {repr(cmake_cache_file)}: {line}")77_, variable, type_, value = matched.groups()78if type_ is None:79type_ = ""80if type_.upper() in ("INTERNAL", "STATIC"):81# CMake internal variable, do not touch82continue83results[variable] = convert_cmake_value_to_python_value(value, type_)84
85return results86