blob: b06e3f3227e9b608381f339c2981aea5216e5fcf [file] [log] [blame]
Ang Li93420002016-05-10 19:11:44 -07001#!/usr/bin/env python3.4
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.
16
17from subprocess import Popen, PIPE
18
Ang Lie2139f12016-05-12 17:39:06 -070019
Ang Li93420002016-05-10 19:11:44 -070020def exe_cmd(*cmds):
21 """Executes commands in a new shell. Directing stderr to PIPE.
22
23 This is fastboot's own exe_cmd because of its peculiar way of writing
24 non-error info to stderr.
25
26 Args:
27 cmds: A sequence of commands and arguments.
28
29 Returns:
30 The output of the command run.
31
32 Raises:
33 Exception is raised if an error occurred during the command execution.
34 """
35 cmd = ' '.join(cmds)
36 proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
37 (out, err) = proc.communicate()
38 if not err:
39 return out
40 return err
41
Ang Lie2139f12016-05-12 17:39:06 -070042
Ang Li93420002016-05-10 19:11:44 -070043class FastbootError(Exception):
44 """Raised when there is an error in fastboot operations."""
45
Ang Lie2139f12016-05-12 17:39:06 -070046
Ang Li93420002016-05-10 19:11:44 -070047class FastbootProxy():
48 """Proxy class for fastboot.
49
50 For syntactic reasons, the '-' in fastboot commands need to be replaced
51 with '_'. Can directly execute fastboot commands on an object:
52 >> fb = FastbootProxy(<serial>)
53 >> fb.devices() # will return the console output of "fastboot devices".
54 """
Ang Lie2139f12016-05-12 17:39:06 -070055
Ang Li93420002016-05-10 19:11:44 -070056 def __init__(self, serial=""):
57 self.serial = serial
58 if serial:
59 self.fastboot_str = "fastboot -s {}".format(serial)
60 else:
61 self.fastboot_str = "fastboot"
62
63 def _exec_fastboot_cmd(self, name, arg_str):
64 return exe_cmd(' '.join((self.fastboot_str, name, arg_str)))
65
66 def args(self, *args):
Ang Lie2139f12016-05-12 17:39:06 -070067 return exe_cmd(' '.join((self.fastboot_str, ) + args))
Ang Li93420002016-05-10 19:11:44 -070068
69 def __getattr__(self, name):
70 def fastboot_call(*args):
71 clean_name = name.replace('_', '-')
72 arg_str = ' '.join(str(elem) for elem in args)
73 return self._exec_fastboot_cmd(clean_name, arg_str)
Ang Lie2139f12016-05-12 17:39:06 -070074
Ang Li93420002016-05-10 19:11:44 -070075 return fastboot_call