#!/usr/bin/python3 """ FORTRAN FLUKA user routine converter to clean up the names of include files with parentheses All occurences and variants of INCLUDE '(ABDFD)' will be replaced by INCLUDE 'abdfd.inc'. """ __authors__ = "C. Theis, V. Vlachoudis" __copyright__ = "Copyright (C) 2019- CERN" __version__ = "1.3 (170221)" import os import re import sys import shutil #--------------------------------------------------------------------------------------------------- # convert the file def convertFORTRAN(fileName): compiledRegEx = re.compile(r'^(\s*INCLUDE\s*[\'"])\((\w+)\)([\'"].*)$', re.IGNORECASE) # read the file into a buffer to allow overwriting it backup = fileName + "~" try: os.remove(backup) except: pass os.rename(fileName, backup) try: outFile = open(fileName, 'w') except IOError as e: print(f"Could not open output file ({e}).") try: print(f"Converting: {fileName}") with open(backup, 'r', encoding='utf-8', errors='replace') as fin: for line in fin: res = compiledRegEx.match( line ) if res is None: outFile.write(line) else: # outFile.write("%s%s.inc%s\n"%res.groups()) outFile.write("%s%s.inc%s\n"%(res.group(1),res.group(2).lower(),res.group(3))) except Exception as e: print(f"Couldn't open file ({e}).") # restore file from backup outFile.close() os.remove(fileName) os.rename(backup, fileName) return outFile.close() # retain permission bits shutil.copymode(backup, fileName) #-------------------------------------------------------------------------------------------------- if __name__ == "__main__": #sys.argv.append( "e:\\temp\\test-file.f" ) print(f"FORTRAN User routine converter Version {__version__} by {__authors__}") print(__copyright__) if len(sys.argv) == 1 or sys.argv[1] == '-h' or sys.argv[1] == '-H': print("Syntax: fluka_src_converter ") print("Please note that wildcards are allowed as well as directories with wildcards") print("e.g: fluka_src_converter mysrc/*") sys.exit() #retrieve file names fileNames = sys.argv[1:] for curFile in fileNames: convertFORTRAN( curFile )