summaryrefslogtreecommitdiff
path: root/bin/flycheck-android-java.py
blob: 656640ec1addf0affaf19d2196061f2aa240348d (plain)
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/python
# -*- coding: utf-8 -*-

import argparse
import errno
import os
import subprocess
import sys
import tempfile

def get_gradle_command_and_project_mtime(dir):
    """Find top-project gradlew or fallback to using gradle on sub-project dir.
While iterating the paths, also check mtime on build.gradle files"""
    topdir = dir
    build_gradle = None
    gradlew = None
    mtime = -1
    while True:
        test = os.path.join(topdir, 'build.gradle')
        if os.path.exists(test):
            if not build_gradle:
                build_gradle = test

            try:
                m = os.path.getmtime(test)
                if m > mtime:
                    mtime = m
            except OSError:
                pass

        test = os.path.join(topdir, 'gradlew')
        if os.path.exists(test):
            gradlew = test
            break

        test = os.path.dirname(topdir)
        if test == topdir:
            break
        topdir = test

    if gradlew:
        cmd = [gradlew, '-p', topdir]
    elif build_gradle:
        topdir = os.path.dirname(build_gradle)
        cmd = ['gradle', '-p', topdir]
    else:
        topdir = ''
        cmd = ['gradle']
    return (cmd, mtime, topdir)

def filter_source_files(files):
    """Remove any item not looking like a Java source file."""
    return [f for f in files if f.endswith('.java')]

def cleanup_output(tmp, real):
    """Remove any file in tmp that is older than the one in real"""
    offset = len(tmp)
    if tmp[-1] != '/':
        offset = offset + 1
    for (dirpath, _, files) in os.walk(tmp):
        realpath = os.path.join(real, dirpath[offset:])
        for filename in files:
            try:
                mtime = os.path.getmtime(os.path.join(realpath, filename))
                tmp = os.path.join(dirpath, filename)
                if os.path.getmtime(tmp) <= mtime:
                    os.remove(tmp)
            except OSError:
                pass

def run_javac(encoding, source, target, bootcp, cp, files, output, args,
              sourcefile, outdir):
    """Execute javac with the given options."""
    command = ['javac']
    if encoding:
        command.extend(['-encoding', encoding])
    if source:
        command.extend(['-source', source])
    if target:
        command.extend(['-target', target])
    if bootcp:
        command.extend(['-bootclasspath', bootcp])
    if outdir:
        command.extend(['-d', outdir])
        tmp = [outdir]
        if output:
            tmp.append(output)
        if cp:
            tmp.extend(cp)
        if tmp:
            command.extend(['-cp', ':'.join(tmp)])

        if os.fork() == 0:
            cleanup_output(outdir, output)
            sys.exit(0)
    else:
        if cp:
            command.extend(['-cp', ':'.join(cp)])
        if output:
            command.extend(['-d', output])
    if [x for x in args if x]:
        command.extend([x for x in args if x])
    command.append(sourcefile)
    if outdir:
        return subprocess.call(command)
    else:
        with tempfile.NamedTemporaryFile(mode='w') as f:
            command.append('@' + f.name)
            for source in filter_source_files(files):
                f.write(source)
                f.write('\n')
                f.flush()
            return subprocess.call(command)

def file_in_list(needle, files):
    """Find needle in files and if so, return the list without needle.
Otherwise return None."""
    if os.path.exists(needle):
        for i in range(0, len(files) - 1):
            if os.path.exists(files[i]) and os.path.samefile(needle, files[i]):
                return files[0:i] + files[i + 1:]
    return None

def split_variant(variant):
    ret = []
    last = 0
    for i in range(0, len(variant)):
        if variant[i:i+1].isupper():
            ret.append(variant[last:i].lower())
            last = i
    ret.append(variant[last:].lower())
    return ret

def match_variant(variant1, variant2):
    v1 = split_variant(variant1)
    v2 = split_variant(variant2)
    return all(x in v1 for x in v2) or all(x in v2 for x in v1)

def figure_out_java_compilation(sessiondir, sourcefile, tempfile, checkstyle,
                                variant, run_gen, force=False):
    """Get options for Java compilation from gradle project and run javac."""
    (cmd, mtime, projectdir) = get_gradle_command_and_project_mtime(
        os.path.dirname(sourcefile))
    output = None
    cached = False
    if sessiondir != None:
        outdir = os.path.join(sessiondir, 'java_output')
        try:
            os.mkdir(outdir)
        except OSError as exc:
            if exc.errno != errno.EEXIST or not os.path.isdir(outdir):
                outdir = None
            pass
        cachefile = os.path.join(sessiondir, 'gradle_java_output')
        try:
            if not force and os.path.getmtime(cachefile) >= mtime:
                with open(cachefile, 'r') as f:
                    output = f.read()
                    cached = True
        except (OSError, IOError):
            pass
    else:
        outdir = None

    if not output:
        flycheck_cmd = cmd + ['-q', '--no-configuration-cache', 'flycheckAndroidJava']
        output = subprocess.check_output(flycheck_cmd, universal_newlines=True)
        if sessiondir != None:
            try:
                with open(cachefile, 'w') as f:
                    f.write(output)
            except IOError:
                pass

    output = output.split('\n')

    data = None
    data_type = None
    variants = []
    gen = []
    ret = 0
    compiled = False
    for line in output:
        if line == '***' or line == '!!!':
            if data_type == '*':
                variants.append({'data': data, 'gen': len(gen)})
            elif data_type == '!' and variants:
                gen.append(data)
            data_type = line[0]
            if data_type == '*':
                data = {}
            else:
                data = []
        elif data_type == '*':
            if line.startswith('variant='):
                data['variant'] = line[8:]
            if line.startswith('args='):
                data['args'] = line[6:-1].split(', ')
            elif line.startswith('encoding='):
                data['encoding'] = line[9:]
            elif line.startswith('bootcp='):
                data['bootcp'] = line[7:]
            elif line.startswith('cp='):
                data['cp'] = line[3:].split(':')
            elif line.startswith('source='):
                data['source'] = line[7:]
            elif line.startswith('target='):
                data['target'] = line[7:]
            elif line.startswith('files='):
                data['files'] = line[6:].split(':')
            elif line.startswith('output='):
                data['output'] = line[7:]
        elif data_type == '!':
            data.append(line)

    if data_type == '*':
        variants.append({'data': data, 'gen': len(gen)})
    elif data_type == '!' and variants:
        gen.append(data)

    fallback = None

    if variant:
        for v in variants:
            data = v['data']
            if 'variant' in data and match_variant(data['variant'], variant):
                if not fallback:
                    fallback = data
                files = file_in_list(sourcefile, data['files'])
                if files:
                    if run_gen and v['gen'] < len(gen):
                        subprocess.call(cmd + ['-q'] + gen[v['gen']])

                    ret = run_javac(data['encoding'], data['source'],
                                    data['target'], data['bootcp'],
                                    data['cp'], files, data['output'],
                                    data['args'], tempfile, outdir)
                    compiled = True
                    break

    if not compiled and variants:
        data = variants[0]['data']
        first = data['variant'] if 'variant' in data else None
        for v in variants:
            data = v['data']
            if first and 'variant' in data and data['variant'] == first:
                if not fallback:
                    fallback = data
                files = file_in_list(sourcefile, data['files'])
                if files:
                    if run_gen and v['gen'] < len(gen):
                        subprocess.call(cmd + ['-q'] + gen[v['gen']])

                    ret = run_javac(data['encoding'], data['source'],
                                    data['target'], data['bootcp'],
                                    data['cp'], files, data['output'],
                                    data['args'], tempfile, outdir)
                    compiled = True
                    break

    if not compiled:
        # Probably need to rerun gradle to find group for sourcefile
        if cached and os.path.exists(sourcefile):
            return figure_out_java_compilation(sessiondir, sourcefile,
                                               tempfile, checkstyle, variant,
                                               run_gen, force=True)
        # OK, perhaps file doesn't exist yet or not yet added to gradle,
        # whatever, assume the first group is good enough
        if fallback:
            ret = run_javac(fallback['encoding'], fallback['source'],
                            fallback['target'], fallback['bootcp'],
                            fallback['cp'], fallback['files'],
                            fallback['output'], fallback['args'],
                            tempfile, outdir)
            compiled = True

    if not ret and checkstyle:
        cmd = ['java']
        if ':' in checkstyle['jar']:
            cmd.extend(['-cp', ':'.join(os.path.abspath(os.path.join(projectdir, jar)) for jar in checkstyle['jar'].split(':')), 'com.puppycrawl.tools.checkstyle.Main'])
        else:
            cmd.extend(['-jar', os.path.abspath(os.path.join(projectdir, checkstyle['jar']))])

        if 'config' in checkstyle:
            cmd.extend(['-c', checkstyle['config']])

        if 'properties' in checkstyle:
            cmd.extend(['-p', checkstyle['properties']])

        cmd.append(tempfile)
        if checkstyle['path']:
            cwd = os.path.join(projectdir, checkstyle['path'])
        elif len(projectdir):
            cwd = projectdir
        else:
            cwd = None
        ret = subprocess.call(cmd, cwd=cwd)

    if not ret and not compiled:
        print("Source file not in project and project seems empty!")
        ret = -1

    return ret

def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--checkstyle-jar')
    parser.add_argument('--checkstyle-path')
    parser.add_argument('--checkstyle-config')
    parser.add_argument('--checkstyle-properties')
    parser.add_argument('--variant')
    parser.add_argument('--skip-gen', dest='gen', action='store_const',
                        const=False, default=True)
    parser.add_argument('sessiondir', nargs='?')
    parser.add_argument('sourcefile')
    parser.add_argument('tempfile', nargs='?')
    args = parser.parse_args(argv[1:])

    sourcefile = args.sourcefile
    tempfile = args.tempfile or sourcefile

    checkstyle = None
    if args.checkstyle_jar:
        checkstyle = {'jar': args.checkstyle_jar,
                      'path': args.checkstyle_path,
                      'config': args.checkstyle_config,
                      'properties': args.checkstyle_properties}

    sourcefile = os.path.abspath(sourcefile)
    return figure_out_java_compilation(args.sessiondir, sourcefile, tempfile,
                                       checkstyle, args.variant, args.gen)

sys.exit(main(sys.argv))