Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·273 lines (230 loc) · 9.55 KB
/
Copy pathcli.py
File metadata and controls
executable file
·273 lines (230 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
""" java2python.cli -> Java to Python compiler script (installed as `j2py`).
This is all very ordinary. We import the package bits, open and read
a file, translate it, and write it out.
"""
import sys
from argparse import ArgumentParser, ArgumentTypeError
from collections import defaultdict
from importlib.metadata import PackageNotFoundError, version as packageVersion
from logging import getLevelNamesMapping, error, exception, warning, info, basicConfig
from os import path, makedirs, walk
from time import time
from io import IOBase
from java2python.compiler import JavaSyntaxError, Module, buildAST, transformAST
from java2python.config import Config
from java2python.lib import escapes
try:
version = packageVersion('java2python')
except PackageNotFoundError:
version = 'unknown'
def logLevel(value):
""" Returns a valid logging level or raises and exception. """
msg = 'invalid loglevel: %r'
logLevels = getLevelNamesMapping()
try:
lvl = int(value)
except (ValueError, ):
name = value.upper()
if name not in logLevels:
raise ArgumentTypeError(msg % value)
lvl = logLevels[name]
else:
if lvl not in logLevels.values():
raise ArgumentTypeError(msg % value)
return lvl
def configFromDir(inname, dirname):
""" Returns a file name from the given config directory. """
name = path.join(dirname, path.basename(path.splitext(inname)[0]))
return '%s.py' % path.abspath(name)
def runMain(options):
""" Runs our main function with profiling if indicated by options. """
if options.profile:
import cProfile, pstats
prof = cProfile.Profile()
prof.runcall(runOneOrMany, options)
stats = pstats.Stats(prof, stream=sys.stderr)
stats.strip_dirs().sort_stats('cumulative')
stats.print_stats().print_callers()
return 0
else:
return runOneOrMany(options)
def runOneOrMany(options):
""" Runs our main transformer with each of the input files. """
infile, outfile = options.inputfile, options.outputfile
if infile and not isinstance(infile, IOBase) and path.isdir(infile):
if outfile and not isinstance(outfile, IOBase) and not path.isdir(outfile):
warning('Must specify output directory or stdout when using input directory.')
return 2
for dirname, _, files in walk(infile):
for name in [name for name in files if name.endswith('.java')]:
fullname = path.join(dirname, name)
options.inputfile = fullname
info('opening %s', fullname)
if outfile and outfile != '-' and not isinstance(outfile, IOBase):
# path.join discards the output directory when the
# walked name is absolute, so mirror the tree with a
# path relative to the input directory instead.
relname = path.relpath(fullname, infile)
full = path.join(outfile, path.splitext(relname)[0] + '.py')
head = path.dirname(full)
if head and not path.exists(head):
makedirs(head)
options.outputfile = full
runTransform(options)
return 0
else:
return runTransform(options)
def runTransform(options):
""" Compile the indicated java source with the given options. """
timed = defaultdict(time)
timed['overall']
filein = fileout = filedefault = '-'
if options.inputfile and not isinstance(options.inputfile, IOBase):
filein = options.inputfile
if options.outputfile and not isinstance(options.outputfile, IOBase):
fileout = options.outputfile
# A copy: one options object is reused for every file of a directory
# walk, and inserting into the original accumulates the configs of
# each file that came before.
configs = list(options.configs)
if options.configdirs and not isinstance(filein, IOBase):
for configdir in options.configdirs:
dirname = configFromDir(filein, configdir)
if path.exists(dirname):
configs.insert(0, dirname)
if options.includedefaults:
configs.insert(0, 'java2python.config.default')
try:
if filein != '-':
with open(filein) as fd:
source = fd.read()
else:
source = sys.stdin.read()
except OSError as exc:
error('could not read %s: %s', filein, exc.strerror or exc)
return exc.errno or 1
timed['comp']
try:
tree = buildAST(source)
except (JavaSyntaxError, ) as exc:
error('could not parse %s: %s', filein, exc)
return 1
except (Exception, ) as exc:
exception('exception while parsing')
return 1
timed['comp_finish']
config = Config(configs)
timed['xform']
transformAST(tree, config)
timed['xform_finish']
timed['visit']
module = Module(config)
module.sourceFilename = path.abspath(filein) if filein != '-' else None
module.name = path.splitext(path.basename(filein))[0] if filein != '-' else '<stdin>'
module.walk(tree)
timed['visit_finish']
timed['encode']
source = str(module)
timed['encode_finish']
timed['overall_finish']
if options.lexertokens:
for idx, tok in enumerate(tree.parser.input.tokens):
print(f'{idx} {tok}', file=sys.stderr)
print(file=sys.stderr)
if options.javaast:
tree.dump(sys.stderr)
print(file=sys.stderr)
if options.pytree:
module.dumpRepr(sys.stderr)
print(file=sys.stderr)
if not options.skipsource:
if fileout == filedefault:
print(source)
else:
with open(fileout, 'w') as output:
print(source, file=output)
if not options.skipcompile:
try:
compile(source, '<string>', 'exec')
except (SyntaxError, ) as ex:
warning('Generated source has invalid syntax. %s', ex)
else:
info('Generated source has valid syntax.')
info('Parse: %.4f seconds', timed['comp_finish'] - timed['comp'])
info('Visit: %.4f seconds', timed['visit_finish'] - timed['visit'])
info('Transform: %.4f seconds', timed['xform_finish'] - timed['xform'])
info('Encode: %.4f seconds', timed['encode_finish'] - timed['encode'])
info('Total: %.4f seconds', timed['overall_finish'] - timed['overall'])
return 0
def isWindows():
""" True if running on Windows. """
return sys.platform.startswith('win')
def configLogging(loglevel):
""" Configure the logging package. """
fmt = '# %(levelname)s %(funcName)s: %(message)s'
basicConfig(level=loglevel, format=fmt)
def configColors(nocolor):
""" Configure the color escapes. """
if isWindows() or nocolor:
escapes.clear()
def configScript(argv):
""" Return an options object from the given argument sequence. """
parser = ArgumentParser(
description='Translate Java source code to Python.',
epilog='Refer to https://github.com/natural/java2python for docs and support.'
)
add = parser.add_argument
add(dest='inputfile', nargs='?',
help='Read from INPUT. May use - for stdin (default).',
metavar='INPUT', default=None)
add(dest='outputfile', nargs='?',
help='Write to OUTPUT. May use - for stdout (default).',
metavar='OUTPUT', default=None)
add('-c', '--config', dest='configs',
help='Use CONFIG file or module. May be repeated.',
metavar='CONFIG', default=[], action='append')
add('-d', '--config-dir', dest='configdirs',
help='Use DIR to match input filename with config filename.',
metavar='DIR', default=[], action='append')
add('-f', '--profile', dest='profile',
help='Profile execution and print results to stderr.',
default=False, action='store_true')
add('-j', '--java-ast', dest='javaast',
help='Print java source AST tree to stderr.',
default=False, action='store_true')
add('-k', '--skip-compile', dest='skipcompile',
help='Skip compile check on translated source.',
default=False, action='store_true')
add('-l', '--log-level', dest='loglevel',
help='Set log level by name or value.',
default='WARN', type=logLevel)
add('-n', '--no-defaults', dest='includedefaults',
help='Ignore default configuration module.',
default=True, action='store_false')
add('-p', '--python-tree', dest='pytree',
help='Print python object tree to stderr.',
default=False, action='store_true')
add('-r', '--no-color', dest='nocolor',
help='Disable color output.' +\
(' No effect on Win OS.' if isWindows() else ''),
default=False, action='store_true')
add('-s', '--skip-source', dest='skipsource',
help='Skip writing translated source; useful when printing trees',
default=False, action='store_true')
add('-t', '--lexer-tokens', dest='lexertokens',
help='Print lexer tokens to stderr.',
default=False, action='store_true')
add('-v', '--version', action='version', version='%(prog)s ' + version)
ns = parser.parse_args(argv)
if ns.inputfile == '-':
ns.inputfile = sys.stdin
if ns.outputfile == '-':
ns.outputfile = sys.stdout
configColors(ns.nocolor)
configLogging(ns.loglevel)
return ns
def main(argv=None):
""" Entry point for the `j2py` console script. """
return runMain(configScript(sys.argv[1:] if argv is None else argv))
if __name__ == '__main__':
sys.exit(main())