1#!/usr/bin/env python3
2#
3#   Copyright 2016 - 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.
16import logging
17import os
18
19from acts.libs.proc import job
20
21COMMIT_ID_ENV_KEY = 'PREUPLOAD_COMMIT'
22REPO_PATH_KEY = 'REPO_PATH'
23GIT_COMMAND = 'git diff-tree --no-commit-id --name-only -r %s'
24YAPF_COMMAND = 'yapf -d -p %s'
25YAPF_OLD_COMMAND = 'yapf -d %s'
26YAPF_INPLACE_FORMAT = 'yapf -p -i %s'
27
28
29def main():
30    if COMMIT_ID_ENV_KEY not in os.environ:
31        logging.error('Missing commit id in environment.')
32        exit(1)
33
34    if REPO_PATH_KEY not in os.environ:
35        logging.error('Missing repo path in environment.')
36        exit(1)
37
38    commit_id = os.environ[COMMIT_ID_ENV_KEY]
39    full_git_command = GIT_COMMAND % commit_id
40
41    files = job.run(full_git_command).stdout.splitlines()
42    full_files = [os.path.abspath(f) for f in files if f.endswith('.py')]
43    if not full_files:
44        return
45
46    files_param_string = ' '.join(full_files)
47
48    result = job.run(YAPF_COMMAND % files_param_string, ignore_status=True)
49    yapf_inplace_format = YAPF_INPLACE_FORMAT
50
51    if result.stdout:
52        logging.error(result.stdout)
53        logging.error('INVALID FORMATTING.')
54        logging.error('Please run:\n'
55                      '%s' % yapf_inplace_format % files_param_string)
56        exit(1)
57
58
59if __name__ == '__main__':
60    main()
61