Skip to content

Instantly share code, notes, and snippets.

@rgov
Created February 3, 2019 21:25
Show Gist options
  • Save rgov/ae6cf30a4dbc59eda0d1a7ebf52fc28c to your computer and use it in GitHub Desktop.
Save rgov/ae6cf30a4dbc59eda0d1a7ebf52fc28c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
'''
This script patches a CMake script to add a check before every macro and
function definition to make sure that an existing definition is not being
replaced.
'''
import sys
from cmakeast import ast
from cmakeast import ast_visitor
if len(sys.argv) != 2:
print('Usage: python3 patch.py CMakeLists.txt', file=sys.stderr)
sys.exit(1)
patches = []
def patch(name, node, depth):
patchee = node.header.arguments[0].contents
patches.append((patchee, node.line))
with open(sys.argv[1], 'r') as f:
body = f.read()
ast_visitor.recurse(
ast.parse(body),
macro_def=patch,
function_def=patch
)
# Insert the patch lines
lines = body.splitlines()
offset = -1
for patchee, line in patches:
print('Patching', patchee)
newlines = [
'if(COMMAND %s)' % patchee,
' message(FATAL_ERROR "Redefinition of %s!")' % patchee,
'endif()'
]
lines[line+offset:line+offset] = newlines
offset += len(newlines)
with open(sys.argv[1], '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