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