blob: 3a63fcfb5d194e4dbaa52311b33ce9b390fdd86b [file] [log] [blame]
Christoffer Quist Adamsenbfe52fd2022-02-15 14:32:52 +01001#!/usr/bin/env python3
Christoffer Quist Adamsen3d14bf22020-03-19 09:40:47 +01002# Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
3# for details. All rights reserved. Use of this source code is governed by a
4# BSD-style license that can be found in the LICENSE file.
5
Christoffer Quist Adamsen4feb9a12023-10-16 11:12:36 +02006import argparse
Christoffer Quist Adamsen3d14bf22020-03-19 09:40:47 +01007import os
8import subprocess
9import sys
10
11import utils
12
13from subprocess import Popen, PIPE
14
Christoffer Quist Adamsen4feb9a12023-10-16 11:12:36 +020015GOOGLE_JAVA_FORMAT_DIFF = os.path.join(utils.THIRD_PARTY, 'google',
Søren Gjesseb557f922024-11-22 09:31:01 +010016 'google-java-format', '1.24.0',
17 'google-java-format-1.24.0', 'scripts',
Christoffer Quist Adamsen4feb9a12023-10-16 11:12:36 +020018 'google-java-format-diff.py')
19
20GOOGLE_YAPF = os.path.join(utils.THIRD_PARTY, 'google/yapf/20231013')
21
22
23def ParseOptions():
24 result = argparse.ArgumentParser()
25 result.add_argument('--no-java',
26 help='Run google-java-format.',
27 action='store_true',
28 default=False)
29 result.add_argument('--python',
30 help='Run YAPF.',
31 action='store_true',
32 default=False)
33 return result.parse_known_args()
34
35
36def FormatJava(upstream):
37 git_diff_process = Popen(['git', 'diff', '-U0', upstream], stdout=PIPE)
38 fmt_process = Popen([sys.executable, GOOGLE_JAVA_FORMAT_DIFF, '-p1', '-i'],
39 stdin=git_diff_process.stdout)
40 git_diff_process.stdout.close()
41 fmt_process.communicate()
42
43
44def FormatPython(upstream):
45 changed_files_cmd = ['git', 'diff', '--name-only', upstream, '*.py']
46 changed_files = subprocess.check_output(changed_files_cmd).decode(
47 'utf-8').splitlines()
48 if not changed_files:
49 return
50 format_cmd = [
51 sys.executable,
52 os.path.join(GOOGLE_YAPF, 'yapf'), '--in-place', '--style', 'google'
53 ]
54 format_cmd.extend(changed_files)
55 yapf_python_path = [GOOGLE_YAPF, os.path.join(GOOGLE_YAPF, 'third_party')]
56 subprocess.check_call(format_cmd,
57 env={'PYTHONPATH': ':'.join(yapf_python_path)})
58
Christoffer Quist Adamsen3d14bf22020-03-19 09:40:47 +010059
60def main():
Christoffer Quist Adamsen4feb9a12023-10-16 11:12:36 +020061 (options, args) = ParseOptions()
62 upstream = subprocess.check_output(['git', 'cl',
63 'upstream']).decode('utf-8').strip()
64 if not options.no_java:
65 FormatJava(upstream)
66 if options.python:
67 FormatPython(upstream)
68
Christoffer Quist Adamsen3d14bf22020-03-19 09:40:47 +010069
70if __name__ == '__main__':
Christoffer Quist Adamsen4feb9a12023-10-16 11:12:36 +020071 sys.exit(main())