1# -*- coding:utf-8 -*-
2# Copyright 2016 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""Common errors thrown when repo preupload checks fail."""
17
18from __future__ import print_function
19
20import os
21import sys
22
23_path = os.path.realpath(__file__ + '/../..')
24if sys.path[0] != _path:
25    sys.path.insert(0, _path)
26del _path
27
28
29class HookResult(object):
30    """A single hook result."""
31
32    def __init__(self, hook, project, commit, error, files=(), fixup_func=None):
33        """Initialize.
34
35        Args:
36          hook: The name of the hook.
37          project: The name of the project.
38          commit: The git commit sha.
39          error: A string representation of the hook's result.  Empty on
40              success.
41          files: The list of files that were involved in the hook execution.
42          fixup_func: A callable that will attempt to automatically fix errors
43              found in the hook's execution.  Returns an non-empty string if
44              this, too, fails.  Can be None if the hook does not support
45              automatically fixing errors.
46        """
47        self.hook = hook
48        self.project = project
49        self.commit = commit
50        self.error = error
51        self.files = files
52        self.fixup_func = fixup_func
53
54    def __bool__(self):
55        return bool(self.error)
56
57    # pylint: disable=nonzero-method
58    def __nonzero__(self):
59        """Python 2/3 glue."""
60        return self.__bool__()
61
62    def is_warning(self):
63        return False
64
65
66class HookCommandResult(HookResult):
67    """A single hook result based on a CompletedProcess."""
68
69    def __init__(self, hook, project, commit, result, files=(),
70                 fixup_func=None):
71        HookResult.__init__(self, hook, project, commit,
72                            result.stderr if result.stderr else result.stdout,
73                            files=files, fixup_func=fixup_func)
74        self.result = result
75
76    def __bool__(self):
77        return self.result.returncode not in (None, 0)
78
79    def is_warning(self):
80        return self.result.returncode == 77
81