|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +import sys |
| 5 | +from collections import defaultdict |
| 6 | +from logging import _levelNames as logLevels, exception, warning, info, basicConfig |
| 7 | +from optparse import Option, OptionParser, OptionValueError |
| 8 | +from os import path |
| 9 | +from time import time |
| 10 | + |
| 11 | +from java2python.compiler import Module, buildAST, transformAST |
| 12 | +from java2python.config import Config |
| 13 | +from java2python.lib.colortools import colors |
| 14 | + |
| 15 | + |
| 16 | +version = '0.5' |
| 17 | + |
| 18 | + |
| 19 | +def isWindows(): |
| 20 | + return sys.platform.startswith('win') |
| 21 | + |
| 22 | + |
| 23 | +def badLogLevel(name, value): |
| 24 | + msg = 'option %s: invalid loglevel: %r' |
| 25 | + raise OptionValueError(msg % (name, value)) |
| 26 | + |
| 27 | + |
| 28 | +def checkLogLevel(option, opt, value): |
| 29 | + try: |
| 30 | + lvl = int(value) |
| 31 | + except (ValueError, ): |
| 32 | + name = value.upper() |
| 33 | + if name not in logLevels: |
| 34 | + badLogLevel(opt, value) |
| 35 | + lvl = logLevels[name] |
| 36 | + else: |
| 37 | + if lvl not in logLevels: |
| 38 | + badLogLevel(opt, value) |
| 39 | + return lvl |
| 40 | + |
| 41 | + |
| 42 | +class LocalOption(Option): |
| 43 | + TYPES = Option.TYPES + ('loglevel', ) |
| 44 | + TYPE_CHECKER = Option.TYPE_CHECKER.copy() |
| 45 | + TYPE_CHECKER['loglevel'] = checkLogLevel |
| 46 | + |
| 47 | + |
| 48 | +def mainProfile(options): |
| 49 | + if options.profile: |
| 50 | + import cProfile, pstats |
| 51 | + prof = cProfile.Profile() |
| 52 | + prof.runcall(main, options) |
| 53 | + stats = pstats.Stats(prof, stream=sys.stderr) |
| 54 | + stats.strip_dirs().sort_stats('cumulative') |
| 55 | + stats.print_stats().print_callers() |
| 56 | + return 0 |
| 57 | + else: |
| 58 | + return main(options) |
| 59 | + |
| 60 | + |
| 61 | +def configFromDir(inname, dirname): |
| 62 | + name = path.join(dirname, path.basename(path.splitext(inname)[0])) |
| 63 | + return '%s.py' % path.abspath(name) |
| 64 | + |
| 65 | + |
| 66 | +def main(options): |
| 67 | + timed = defaultdict(time) |
| 68 | + timed['overall'] |
| 69 | + |
| 70 | + filein = fileout = filedefault = '-' |
| 71 | + if options.inputfile and not isinstance(options.inputfile, file): |
| 72 | + filein = options.inputfile |
| 73 | + if options.outputfile and not isinstance(options.outputfile, file): |
| 74 | + fileout = path.basename(options.outputfile) |
| 75 | + elif fileout != filedefault: |
| 76 | + fileout = '%s.py' % (path.splitext(filein)[0]) |
| 77 | + |
| 78 | + configs = options.configs |
| 79 | + if options.configdir and not isinstance(filein, file): |
| 80 | + dirconfigname = configFromDir(filein, options.configdir) |
| 81 | + if path.exists(dirconfigname): |
| 82 | + configs.insert(0, dirconfigname) |
| 83 | + if options.includedefaults: |
| 84 | + configs.insert(0, 'java2python.config.default') |
| 85 | + |
| 86 | + try: |
| 87 | + if filein != '-': |
| 88 | + source = open(filein).read() |
| 89 | + else: |
| 90 | + source = sys.stdin.read() |
| 91 | + except (IOError, ), exc: |
| 92 | + code, msg = exc.args[0:2] |
| 93 | + print 'IOError: %s.' % (msg, ) |
| 94 | + return code |
| 95 | + |
| 96 | + config = Config(configs) |
| 97 | + timed['comp'] |
| 98 | + try: |
| 99 | + tree = buildAST(source, config) |
| 100 | + except (Exception, ), exc: |
| 101 | + exception('exception while parsing') |
| 102 | + return 1 |
| 103 | + timed['comp_finish'] |
| 104 | + |
| 105 | + timed['xform'] |
| 106 | + transformAST(tree, config) |
| 107 | + timed['xform_finish'] |
| 108 | + |
| 109 | + timed['visit'] |
| 110 | + module = Module(config) |
| 111 | + module.sourceFilename = path.abspath(filein) if filein != '-' else None |
| 112 | + module.name = path.splitext(path.basename(filein))[0] if filein != '-' else '<stdin>' |
| 113 | + module.walk(tree) |
| 114 | + timed['visit_finish'] |
| 115 | + |
| 116 | + timed['encode'] |
| 117 | + source = unicode(module) |
| 118 | + timed['encode_finish'] |
| 119 | + timed['overall_finish'] |
| 120 | + |
| 121 | + if options.javaast: |
| 122 | + tree.dump(sys.stderr) |
| 123 | + print >> sys.stderr |
| 124 | + |
| 125 | + if options.pytree: |
| 126 | + module.dumpRepr(sys.stderr) |
| 127 | + print >> sys.stderr |
| 128 | + |
| 129 | + if not options.skipsource: |
| 130 | + if fileout == filedefault: |
| 131 | + output = sys.stdout |
| 132 | + else: |
| 133 | + output = open(fileout, 'w') |
| 134 | + module.name = path.splitext(filein)[0] if filein != '-' else '<stdin>' |
| 135 | + print >> output, source |
| 136 | + |
| 137 | + try: |
| 138 | + compile(source, '<string>', 'exec') |
| 139 | + except (SyntaxError, ), ex: |
| 140 | + warning('Generated source has invalid syntax.') |
| 141 | + else: |
| 142 | + info('Generated source has valid syntax.') |
| 143 | + |
| 144 | + info('Parse: %.4f seconds', timed['comp_finish'] - timed['comp']) |
| 145 | + info('Visit: %.4f seconds', timed['visit_finish'] - timed['visit']) |
| 146 | + info('Transform: %.4f seconds', timed['xform_finish'] - timed['xform']) |
| 147 | + info('Encode: %.4f seconds', timed['encode_finish'] - timed['encode']) |
| 148 | + info('Total: %.4f seconds', timed['overall_finish'] - timed['overall']) |
| 149 | + return 0 |
| 150 | + |
| 151 | + |
| 152 | +def config(argv): |
| 153 | + parser = OptionParser(option_class=LocalOption, version='%prog '+version) |
| 154 | + addopt = parser.add_option |
| 155 | + addopt('-i', '--input', dest='inputfile', |
| 156 | + help='Read from INPUTFILE. May use - for stdin.', |
| 157 | + metavar='INPUTFILE', default=None) |
| 158 | + addopt('-o', '--output', dest='outputfile', |
| 159 | + help='Write to OUTPUTFILE. May use - for stdout.', |
| 160 | + metavar='OUTPUTFILE', default=None) |
| 161 | + addopt('-c', '--config', dest='configs', |
| 162 | + help='Use CONFIG file or module. May be repeated.', |
| 163 | + metavar='CONFIG', default=[], |
| 164 | + action='append') |
| 165 | + addopt('-d', '--configdir', dest='configdir', |
| 166 | + help='Use DIR to match input filename with config filename.', |
| 167 | + metavar='DIR', default=None) |
| 168 | + addopt('-n', '--nodefaults', dest='includedefaults', |
| 169 | + help='Ignore default configuration module.', |
| 170 | + default=True, action='store_false') |
| 171 | + addopt('-l', '--loglevel', dest='loglevel', |
| 172 | + help='Set log level by name or value.', |
| 173 | + default='WARN', type='loglevel') |
| 174 | + addopt('-p', '--python-tree', dest='pytree', |
| 175 | + help='Print python object tree to stderr.', |
| 176 | + default=False, action='store_true') |
| 177 | + addopt('-j', '--java-ast', dest='javaast', |
| 178 | + help='Print java source AST tree to stderr.', |
| 179 | + default=False, action='store_true') |
| 180 | + addopt('-f', '--profile', dest='profile', |
| 181 | + help='Profile execution and print results to stderr.', |
| 182 | + default=False, action='store_true') |
| 183 | + addopt('-s', '--skip-source', dest='skipsource', |
| 184 | + help='Skip writing translated source; useful when printing trees', |
| 185 | + default=False, action='store_true') |
| 186 | + addopt('-r', '--nocolor', dest='nocolor', |
| 187 | + help='Disable color output.' +\ |
| 188 | + (' No effect on Win OS.' if isWindows() else ''), |
| 189 | + default=False, action='store_true') |
| 190 | + |
| 191 | + options, args = parser.parse_args(argv) |
| 192 | + if len(args) > 2: |
| 193 | + parser.error('Only one input file supported.') |
| 194 | + elif len(args) == 2: |
| 195 | + options.inputfile = args[1] |
| 196 | + if options.inputfile == '-': |
| 197 | + options.inputfile = sys.stdin |
| 198 | + if options.outputfile == '-': |
| 199 | + options.outputfile = sys.stdout |
| 200 | + ## these next statements don't belong here, but this is as good a |
| 201 | + ## place as any. |
| 202 | + if isWindows() or options.nocolor: |
| 203 | + colors.clear() |
| 204 | + fmt = '# %(levelname)s %(funcName)s: %(message)s' |
| 205 | + basicConfig(level=options.loglevel, format=fmt) |
| 206 | + return options |
| 207 | + |
| 208 | + |
| 209 | +if __name__ == '__main__': |
| 210 | + sys.exit(mainProfile(config(sys.argv))) |
0 commit comments