Once in a while you want to extract some values from a source file. For example if you want to extract a version number from code to process in a CI server.
This example uses the python clang bindings to parse a cpp file and extracts a version number form it.
This example used some assumptions about what the code looks like but you can easily modify it to fit your needs.
Lets assume the following content to be available in a version.cpp file
...
static const int major = 1;
static const int minor = 10;
static const int revision = 11;
...
You can use the following python snippet to extract this and format it nicely to stdout.
from clang.cindex import *
# Initialize the Clang index
index = Index.create()
# Parse the C++ file
tu = index.parse('version.cpp')
# Find the variable of interest
major = None
minor = None
revision = None
for cursor in tu.cursor.walk_preorder():
if cursor.kind == CursorKind.VAR_DECL :
if cursor.spelling == 'major':
major = [t.spelling for t in cursor.get_tokens()][-1]
if cursor.spelling == 'minor':
minor = [t.spelling for t in cursor.get_tokens()][-1]
if cursor.spelling == 'revision':
revision = [t.spelling for t in cursor.get_tokens()][-1]
print(major + '.' + minor + '.' + revision)
This nicely outputs 1.10.11
to stdout
Hope someone finds this example helpful.