#!/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'^@([^@\s]+)', ] pat_lst = list( map( re.compile, lst ) ) def match_path(s): for p in pat_lst: m = p.match( s ) if m and m.groups(): path = cut_quote( m.group( 1 ) ) opts = p.sub( '', s ).split() return ( path, opts ) return ( None, '' ) paths = [ '-' ] def cvt_opts(r, opts): for opt in opts: delim = '=' if delim in opt: i = opt.index( delim ) (k, v) = ( opt[ : i ], opt[ i + len( delim ) : ] ) r = r.replace( k, v ) return r search_dirs = [ os.path.dirname( __file__ ) ] def inc_text(s): (path, opts) = match_path( s ) if path == None: return None path_lst = [ path ] if not path.startswith( '/' ): path_lst += list( map( lambda dir_: os.path.join( dir_, path ), search_dirs ) ) 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 empty.new( s=cut_tail_nl( r ), opts=opts ) 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 = cvt_opts( r.s, r.opts ) if '-nr' not in r.opts: s = exp( s ) 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() (s, opt) = nkf.to_str( b ) s = inc.exp( s ) b = nkf.str_to( s, opt ) nkf.put_stdout( b ) # EOF