#!/usr/bin/env python import os import re import empty import nkf import dbg def read_str(path): r = False with open( path, 'rb' ) as f: try: b = f.read() ( r, opt ) = nkf.to_str( b ) except: pass return r cut_tail_nl = lambda s: s[ : -1 ] if s and s[ -1 ] == '\n' else s 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 def new( lst=[] ): lst += [ r'^# *include +(.*)$', r'^@ *include +(.*)$', r'^@ *inc +(.*)$', r'^@(.*)$', ] pat_lst = list( map( re.compile, lst ) ) def match_path(s): for p in pat_lst: if p.match( s ): return cut_quote( p.sub( r'\1', s ) ) return None paths = [ '-' ] def inc_text(s): path = match_path( s ) if path == None: return None path_lst = [ path ] if not path.startswith( '/' ): path_lst.append( os.path.join( os.path.split( __file__ )[ 0 ], path ) ) for path in path_lst: if os.path.exists( path ): if path in paths: return True r = read_str( path ) if r == False: return False paths.append( path ) return cut_tail_nl( r ) return False def exp_line(i, s): r = inc_text( s ) if r == False: dbg.err_exit( 'err {}, {} L{}\n'.format( s, paths[ -1 ], i+1 ) ) if r == None: return s if r == True: return '' s = exp( r ) paths.pop() return s exp = lambda s: '\n'.join( map( lambda i_s: exp_line( *i_s ), enumerate( s.split( '\n' ) ) ) ) return empty.new( locals() ) if __name__ == "__main__": inc = new() b = nkf.get_stdin() opt = nkf.guess( b ) s = nkf.dec( nkf.cvt( b, '-u' ) ) s = inc.exp( s ) b = nkf.cvt( nkf.enc( s ), opt ) nkf.put_stdout( b ) # EOF