Created
February 5, 2019 17:34
-
-
Save rgov/ee76c4d0e604afcfb147c4f92bb9b1c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| ''' | |
| This script finds CMakeLists.txt files and patches them so that each test | |
| explicitly declares what it depends on. | |
| ''' | |
| import os | |
| import re | |
| import sys | |
| from cmakeast import ast | |
| from cmakeast import ast_visitor | |
| root = sys.argv[1] | |
| # Find all of the CMakeLists.txt files | |
| cmakelists = [] | |
| for root, dirs, files in os.walk(root): | |
| for name in files: | |
| if name == 'CMakeLists.txt': | |
| cmakelists.append(os.path.join(root, name)) | |
| # Handle each file | |
| for path in cmakelists: | |
| print('Processing', path) | |
| tests = [] | |
| tests_with_property = [] | |
| def handle_call(name, node, depth): | |
| if node.name == 'add_test': | |
| if node.arguments[0].contents == 'NAME': | |
| testname = node.arguments[1].contents | |
| command = node.arguments[3].contents | |
| else: | |
| testname = node.arguments[0].contents | |
| command = node.arguments[1].contents | |
| tests.append((node.line - 1, testname, command)) | |
| elif node.name == 'set_tests_properties': | |
| # TODO: We should try to figure out if the property is already set | |
| pass | |
| with open(path, 'r') as f: | |
| body = f.read() | |
| ast_visitor.recurse( | |
| ast.parse(body), | |
| function_call=handle_call | |
| ) | |
| if not tests: | |
| continue | |
| # Apply the patches | |
| lines = body.splitlines() | |
| offset = 1 | |
| for line, testname, command in tests: | |
| print('Patching test', testname) | |
| newlines = [ | |
| 'set_tests_properties(%s PROPERTIES REQUIRED_FILES %s)' \ | |
| % (testname, command) | |
| ] | |
| # Apply the correct indentation | |
| indent = re.match(r'^(\s*)', lines[line]).group(1) | |
| newlines = [ indent+l for l in newlines ] | |
| # Insert it | |
| lines[line+offset:line+offset] = newlines | |
| offset += len(newlines) | |
| # Add a newline to the end of the file if it is missing one | |
| if lines[-1] != '': | |
| lines.append('') | |
| with open(path, 'w') as f: | |
| f.write('\n'.join(lines)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment