Created
December 10, 2013 16:01
-
-
Save johntyree/7893054 to your computer and use it in GitHub Desktop.
Generic preprocessor
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
#!/usr/bin/env python | |
# coding: utf8 | |
# GistID: 7893054 | |
""" A generic preprocessor. | |
Replace `#include "<file>"` lines with file contents. | |
If the line starts with '//' then leave the include line in the output | |
for reference. | |
""" | |
import os | |
import re | |
import sys | |
include_regex = re.compile( | |
r'''\s*(?P<comment>//)?\s*#include\s+["']?(?P<filename>[^'"]+)''' | |
) | |
def digest(line): | |
""" Test a line against include_regex. If match, include the | |
contents of the file inline. | |
""" | |
m = include_regex.match(line) | |
if m: | |
fields = m.groupdict() | |
filename = m.groupdict()['filename'] | |
with open(filename, 'rb') as fin: | |
if fields['comment']: | |
return line + fin.read() | |
else: | |
return fin.read() | |
else: | |
return line | |
def main(): | |
"""Run main.""" | |
if len(sys.argv) > 1: | |
fullpath = os.path.abspath(sys.argv[1].strip()) | |
directory, filename = os.path.split(fullpath) | |
os.chdir(directory) | |
with open(filename, 'rb') as fin: | |
for line in fin: | |
sys.stdout.write(digest(line)) | |
else: | |
for line in sys.stdin: | |
sys.stdout.write(digest(line)) | |
return 0 | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment