#!/usr/bin/env python import sys import os import six import re pat_lst = [] def init(): lst = [ r'^# *include +(.*)$', r'^@ *include +(.*)$', r'^@ *inc +(.*)$', r'^@(.*)$', ] pat_lst.extend( list( map( re.compile, lst ) ) ) def cut_quote(s): if s and len( s ) >= 2: for q in ( "''", '""', '<>' ): if s[ 0 ] == q[ 0 ] and s[ -1 ] == q[ -1 ]: return s[ 1 : -1 ] return s paths = [ '-' ] is_dbl_paths = lambda : paths[ -1 ] in paths[ : -1 ] def inc_text(s): path = None for p in pat_lst: if p.match( s ): path = cut_quote( p.sub( r'\1', s ) ) break if path == None: return None path_lst = [ path ] if not path.startswith( '/' ): path_lst.append( os.path.join( os.path.split( __file__ )[ 0 ], path ) ) r = False for path in path_lst: if os.path.exists( path ): with open( path, 'rb' ) as f: try: r = f.read().decode( 'utf-8' ) paths.append( path ) except: pass break return r def err(s, i): sys.stderr.write( 'err {}, {} L{}\n'.format( s, paths[ -1 ], i+1 ) ) sys.exit( 1 ) cut_tail_nl = lambda s: s[ : -1 ] if s and s[ -1 ] == '\n' else s def inc_exp(s): def inc_exp_line(i_s): (i, s) = i_s r = inc_text( s ) if r == False: err( s, i ) if r != None: s = '' if not is_dbl_paths(): s = inc_exp( cut_tail_nl( r ) ) paths.pop() return s return '\n'.join( map( inc_exp_line, enumerate( s.split( '\n' ) ) ) ) if __name__ == "__main__": init() f = sys.stdin if six.PY2 else sys.stdin.buffer s = f.read().decode( 'utf-8' ) s = inc_exp( s ) f = sys.stdout if six.PY2 else sys.stdout.buffer f.write( s.encode( 'utf-8' ) ) # EOF