check_guard.py 1.53 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#!/usr/bin/python3

from sys import argv
from os.path import basename, dirname, splitext
from re import compile
from io import StringIO

guard_re = compile(r'#ifndef\s+(.*)')
guard_re2 = compile(r'#define\s+(.*)')

def extract_guard(filename):
	f = open(filename)
	it = iter(f)
	for line in it:
		m = guard_re.match(line)
		if m:
			nl = next(it)
			m2 = guard_re2.match(nl)
			if not m2 or m2.group(1) != m.group(1):
				print('\033[32mError:\033[0m file "{}" has inconsistent include guard.'.format(filename))
			return m.group(1)
	return None

def print_all_caps_from_camel_case(toprint, out):
	skip = True
	for c in toprint:
		if c.isupper() and not skip:
			out.write('_')
			skip = True
		else:
31
			skip = c == "_"
32 33 34 35 36
		out.write(c.upper())

def guard_from_filename(filename):
	guard = StringIO('')
	guard.write('_')
37

38 39 40
	d = dirname(filename)
	if d == 'Patate':
		guard.write('PATATE')
41 42 43 44
	elif d.startswith('Patate/common/') or d.startswith('examples/Vitelotte/common'):
		print_all_caps_from_camel_case(d.replace('/', '_'), guard)
	elif d.startswith('examples/'):
		print_all_caps_from_camel_case(basename(d), guard)
45 46 47 48
	else:
		print_all_caps_from_camel_case(basename(dirname(d)), guard)

	guard.write('_')
49

50 51 52 53
	name, ext = splitext(basename(filename))
	print_all_caps_from_camel_case(name, guard)

	guard.write('_')
54

55 56 57
	return guard.getvalue()

current = extract_guard(argv[1])
58
target = guard_from_filename(argv[1])
59

60
if current == target:
61 62
	print('\033[32m{}\033[0m: {}'.format(argv[1], current))
else:
63
	print('\033[31m{}\033[0m: {} - {}'.format(argv[1], current, target))