1#!/usr/bin/env python3
2#
3#   Copyright 2019 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16
17import logging
18import os
19import subprocess
20import sys
21
22PYTHONPATH_KEY = 'PYTHONPATH'
23COMMIT_ID_ENV_KEY = 'PREUPLOAD_COMMIT'
24ANDROID_BUILD_TOP_KEY = 'ANDROID_BUILD_TOP'
25DEFAULT_YAPF_DIR = 'external/yapf'
26GIT_COMMAND = ['git', 'diff-tree', '--no-commit-id', '--name-only', '--diff-filter=d']
27
28
29def main():
30    """
31    A Python commit formatter using YAPF
32
33    Caveat: if you modify a file, the entire file will be formatted, instead of
34            the diff
35    :return:
36    """
37    if COMMIT_ID_ENV_KEY not in os.environ:
38        logging.error('Missing PREUPLOAD_COMMIT in environment.')
39        exit(1)
40
41    # Gather changed Python files
42    commit_id = os.environ[COMMIT_ID_ENV_KEY]
43    full_git_command = GIT_COMMAND + ['-r', commit_id]
44    files = subprocess.check_output(full_git_command).decode('utf-8').splitlines()
45    full_files = [os.path.abspath(f) for f in files if f.endswith('.py')]
46    if not full_files:
47        return
48
49    if ANDROID_BUILD_TOP_KEY not in os.environ:
50        logging.error('Missing ANDROID_BUILD_TOP in environment.')
51        exit(1)
52
53    # Find yapf in Android code tree
54    yapf_dir = os.path.join(os.environ[ANDROID_BUILD_TOP_KEY], DEFAULT_YAPF_DIR)
55    yapf_binary = os.path.join(yapf_dir, 'yapf')
56
57    # Run YAPF
58    full_yapf_command = ["%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY, yapf_dir), 'python3', yapf_binary, '-d', '-p'
59                        ] + full_files
60    environment = os.environ.copy()
61    environment[PYTHONPATH_KEY] = environment[PYTHONPATH_KEY] + ":" + yapf_dir
62    result = subprocess.run(full_yapf_command[1:], env=environment, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
63
64    if result.returncode != 0 or result.stdout:
65        logging.error(result.stdout.decode('utf-8').strip())
66        logging.error('INVALID FORMATTING, return code %d', result.returncode)
67        logging.error('To re-run the format command:\n\n' '    %s\n' % ' '.join(full_yapf_command))
68        yapf_inplace_format = ' '.join(
69            ["%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY, yapf_dir), 'python3', yapf_binary, '-p', '-i'] + full_files)
70        logging.error('If this is a legitimate format error, please run:\n\n' '    %s\n' % yapf_inplace_format)
71        logging.error('CAVEAT: Currently, this format the entire Python file if you modify even part of it')
72        exit(1)
73
74
75if __name__ == '__main__':
76    main()
77