1# Copyright 2016 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://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, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15 16"""Expands CMake variables in a text file.""" 17 18import re 19import sys 20 21_CMAKE_DEFINE_REGEX = re.compile(r"\s*#cmakedefine\s+([A-Za-z_0-9]*)(\s.*)?$") 22_CMAKE_DEFINE01_REGEX = re.compile(r"\s*#cmakedefine01\s+([A-Za-z_0-9]*)") 23_CMAKE_VAR_REGEX = re.compile(r"\${([A-Za-z_0-9]*)}") 24_CMAKE_ATVAR_REGEX = re.compile(r"@([A-Za-z_0-9]*)@") 25 26 27def _parse_args(argv): 28 """Parses arguments with the form KEY=VALUE into a dictionary.""" 29 result = {} 30 for arg in argv: 31 k, v = arg.split("=") 32 result[k] = v 33 return result 34 35 36def _expand_variables(input_str, cmake_vars): 37 """Expands ${VARIABLE}s and @VARIABLE@s in 'input_str', using dictionary 'cmake_vars'. 38 39 Args: 40 input_str: the string containing ${VARIABLE} or @VARIABLE@ expressions to expand. 41 cmake_vars: a dictionary mapping variable names to their values. 42 43 Returns: 44 The expanded string. 45 """ 46 def replace(match): 47 if match.group(1) in cmake_vars: 48 return cmake_vars[match.group(1)] 49 return "" 50 return _CMAKE_ATVAR_REGEX.sub(replace,_CMAKE_VAR_REGEX.sub(replace, input_str)) 51 52 53def _expand_cmakedefines(line, cmake_vars): 54 """Expands #cmakedefine declarations, using a dictionary 'cmake_vars'.""" 55 56 # Handles #cmakedefine lines 57 match = _CMAKE_DEFINE_REGEX.match(line) 58 if match: 59 name = match.group(1) 60 suffix = match.group(2) or "" 61 if name in cmake_vars: 62 return "#define {}{}\n".format(name, 63 _expand_variables(suffix, cmake_vars)) 64 else: 65 return "/* #undef {} */\n".format(name) 66 67 # Handles #cmakedefine01 lines 68 match = _CMAKE_DEFINE01_REGEX.match(line) 69 if match: 70 name = match.group(1) 71 value = cmake_vars.get(name, "0") 72 return "#define {} {}\n".format(name, value) 73 74 # Otherwise return the line unchanged. 75 return _expand_variables(line, cmake_vars) 76 77 78def main(): 79 cmake_vars = _parse_args(sys.argv[1:]) 80 for line in sys.stdin: 81 sys.stdout.write(_expand_cmakedefines(line, cmake_vars)) 82 83 84if __name__ == "__main__": 85 main() 86