Source code for mojo.libdist.setPrecompileFlag

"""
setPrecompileFlag
=================
provides methods to set value for constants in headerfiles
"""


import re
import tempfile
from shutil import move

from ..bricabrac.fileIO import removeFile


[docs]def replaceInFile(filename, pattern, subst): """ replace pattern in file with subst :param filename: name of the file :param pattern: pattern to replace :param subst: replacement for the pattern :type filename: string :type pattern: string :type subst: string :return: true if a pattern was replaced :rtype: boolean """ replaced = False # open newFile and oldFile with tempfile.NamedTemporaryFile(mode='w', delete=False) as newFile: # go through all lines in the old file # if pattern is found in line replace pattern with subst # else don't change the line # write line in newFile for line in open(filename): if re.search(pattern, line): newLine = re.sub(pattern, subst, line) replaced = True else: newLine = line newFile.write(newLine) # remove original file removeFile(filename) # Move new file move(newFile.name, filename) return replaced
[docs]def setPreprocessorMacroInFile(filename, variable, newValue): """matches a preprocessor define in a given file and rewrites it with the new value :param filename: name of the file :param variableName: name of the variable :param value: value to set :type filename: string :type variableName: string :type value: string """ return replaceInFile(filename, r"#\s*define\s*" + variable + r"\s+\w*", "#define " + variable + " " + newValue)
[docs]def setPrecompile(filename, variableName, value, verbose=0): """ creates pattern and subst using variableName and value calls function replaceInFile and returns its return value :param filename: name of the file :param variableName: name of the variable :param value: value to set :param verbose: verbosity level :type filename: string :type variableName: string :type value: string :type verbose: integer """ if verbose: print(f"Setting variable '{variableName}' to '{value}' in file '{filename}'") replaced = setPreprocessorMacroInFile(filename, variableName, value) if not replaced: headername = re.findall("trace_suite.*", filename)[0] message = f"Can't find constant '{variableName}' in headerfile '{headername}'" raise NotFoundConstantException(message)
[docs]class NotFoundConstantException(Exception): def __init__(self, message): super(NotFoundConstantException, self).__init__() self.message = message def __str__(self): return self.message