1#
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
16from subprocess import Popen, PIPE
17
18
19def exe_cmd(*cmds):
20    """Executes commands in a new shell. Directing stderr to PIPE.
21
22    This is fastboot's own exe_cmd because of its peculiar way of writing
23    non-error info to stderr.
24
25    Args:
26        cmds: A sequence of commands and arguments.
27
28    Returns:
29        The output of the command run.
30
31    Raises:
32        Exception is raised if an error occurred during the command execution.
33    """
34    cmd = ' '.join(cmds)
35    proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
36    (out, err) = proc.communicate()
37    if not err:
38        return out
39    return err
40
41
42class FastbootError(Exception):
43    """Raised when there is an error in fastboot operations."""
44
45
46class FastbootProxy():
47    """Proxy class for fastboot.
48
49    For syntactic reasons, the '-' in fastboot commands need to be replaced
50    with '_'. Can directly execute fastboot commands on an object:
51    >> fb = FastbootProxy(<serial>)
52    >> fb.devices() # will return the console output of "fastboot devices".
53    """
54
55    def __init__(self, serial=""):
56        self.serial = serial
57        if serial:
58            self.fastboot_str = "fastboot -s {}".format(serial)
59        else:
60            self.fastboot_str = "fastboot"
61
62    def _exec_fastboot_cmd(self, name, arg_str):
63        return exe_cmd(' '.join((self.fastboot_str, name, arg_str)))
64
65    def args(self, *args):
66        return exe_cmd(' '.join((self.fastboot_str, ) + args))
67
68    def __getattr__(self, name):
69        def fastboot_call(*args):
70            clean_name = name.replace('_', '-')
71            arg_str = ' '.join(str(elem) for elem in args)
72            return self._exec_fastboot_cmd(clean_name, arg_str)
73
74        return fastboot_call
75