Last active
August 16, 2019 17:07
-
-
Save Piping/92ff1bd1f3f272dc6848b04d9556809f to your computer and use it in GitHub Desktop.
Extract C Code from source code automatically. Good for unittesting. -- requires ctags
This file contains 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
import sys | |
cmd = sys.argv[1] | |
f = open(sys.argv[2]) | |
lines = [ l for l in f ] | |
f2 = sys.argv[3] | |
def find_struct_or_var_range(lines, i): | |
pass | |
def find_function_range(lines, i): | |
bracket=0 | |
end = i | |
start = i | |
while True: | |
l = lines[end-1] | |
go_out = 0 | |
for c in l: | |
if c == '{': | |
bracket += 1 | |
if c == '}': | |
bracket -= 1 | |
if bracket == 0: | |
go_out = 1; | |
break | |
if go_out == 1: | |
break | |
end += 1 | |
while True: | |
l = lines[start-2] | |
l = l.strip() | |
if l[-1:] == '}' or l[-1:] == ';': | |
break | |
start -= 1 | |
return (start,end) | |
if cmd == '--func': | |
n = int(sys.argv[3]) | |
(i,j) = find_function_range(lines,n) | |
print "".join(lines[i:j]) | |
elif cmd == '--decl': | |
n = int(sys.argv[3]) | |
(i,j) = find_struct_or_var_range(lines,n) | |
print "".join(lines[i:j]) | |
elif cmd == '--update': | |
(i,j) = (0,0) | |
for index, l in enumerate(lines): | |
if l == '/* PASTE THE CODE START */\n': | |
i = index; | |
if l == '/* PASTE THE CODE END */\n': | |
j = index; | |
if (i,j) == (0,0): | |
print sys.argv[2] + " is not valid unittest file format\n" | |
exit(1) | |
of = open(sys.argv[3]) | |
output = lines[:i+1] | |
for l in of: | |
output.append(l) | |
output.extend(lines[j:]) | |
print "".join(output) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
python extract_c_code.py --cmds source.c <line_number | unittest.c>
#extract definition of functions python extract_c_code.py --func source.c line_number