• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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']
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    if ANDROID_BUILD_TOP_KEY not in os.environ:
42        logging.error('Missing ANDROID_BUILD_TOP in environment.')
43        exit(1)
44
45    # Gather changed Python files
46    commit_id = os.environ[COMMIT_ID_ENV_KEY]
47    full_git_command = GIT_COMMAND + ['-r', commit_id]
48    files = subprocess.check_output(full_git_command).decode(
49        'utf-8').splitlines()
50    full_files = [os.path.abspath(f) for f in files if f.endswith('.py')]
51    if not full_files:
52        return
53
54    # Find yapf in Android code tree
55    yapf_dir = os.path.join(os.environ[ANDROID_BUILD_TOP_KEY], DEFAULT_YAPF_DIR)
56    yapf_binary = os.path.join(yapf_dir, 'yapf')
57
58    # Run YAPF
59    full_yapf_command = [
60        "%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY, yapf_dir), 'python3',
61        yapf_binary, '-d', '-p'
62    ] + full_files
63    environment = os.environ.copy()
64    environment[PYTHONPATH_KEY] = environment[PYTHONPATH_KEY] + ":" + yapf_dir
65    result = subprocess.run(
66        full_yapf_command[1:],
67        env=environment,
68        stderr=subprocess.STDOUT,
69        stdout=subprocess.PIPE)
70
71    if result.returncode != 0 or result.stdout:
72        logging.error(result.stdout.decode('utf-8').strip())
73        logging.error('INVALID FORMATTING, return code %d', result.returncode)
74        logging.error('To re-run the format command:\n\n'
75                      '    %s\n' % ' '.join(full_yapf_command))
76        yapf_inplace_format = ' '.join([
77            "%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY,
78                           yapf_dir), 'python3', yapf_binary, '-p', '-i'
79        ] + full_files)
80        logging.error('If this is a legitimate format error, please run:\n\n'
81                      '    %s\n' % yapf_inplace_format)
82        logging.error(
83            'CAVEAT: Currently, this format the entire Python file if you modify even part of it'
84        )
85        exit(1)
86
87
88if __name__ == '__main__':
89    main()
90