Skip to content

Instantly share code, notes, and snippets.

@geky
Created August 24, 2017 22:44
Show Gist options
  • Save geky/1134d897e9b6288116ef348bafb50e2a to your computer and use it in GitHub Desktop.
Save geky/1134d897e9b6288116ef348bafb50e2a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import re
import argparse
import json
import os.path
import itertools
# args
p = argparse.ArgumentParser()
p.add_argument('headers', nargs='*',
help='Header files to parse for defines')
p.add_argument('-D', action='append', default=[],
help='Argument define, similar to -D passed to gcc')
args = p.parse_args()
# grab the current config file, if any
try:
try:
f = open('mbed_lib.json')
app = False
print 'loaded mbed_lib.json'
except IOError:
f = open('mbed_app.json')
app = True
print 'loaded mbed_app.json'
config = json.load(f)
except IOError:
config = {}
app = False
if not app and 'name' not in config:
config['name'] = os.path.relpath('.', '..')
if 'config' not in config:
config['config'] = {}
# massive iterator through all defines
def headerdefines():
for header in args.headers:
with open(header) as f:
print 'loading %s' % header
# hackily join multilines
lines = iter(f)
for line in lines:
while line.endswith('\\\n'):
line = line[:-2] + next(lines)
# one big regex
m = re.match('\s*#\s*define\s+'
'([a-zA-Z_][a-zA-Z0-9_]*)'
'(?![\(a-zA-Z0-9])(.*)', line)
if m:
yield m.group(1), m.group(2)
def argdefines():
for pair in args.D:
if '=' in pair:
yield pair.split('=')
else:
yield pair, ''
alldefines = itertools.chain(headerdefines(), argdefines())
# update config object
for name, value in alldefines:
name = name.strip()
value = value.strip()
key = name.lower().replace('_', '-')
if name in config:
print 'updating %s' % key
else:
print 'adding %s' % key
config['config'][key] = {
'macro_name': name,
'value': value
}
if app:
path = 'mbed_app.json'
else:
path = 'mbed_lib.json'
with open(path, 'w') as f:
json.dump(config, f, indent=4, sort_keys=True)
print 'done'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment