aboutsummaryrefslogtreecommitdiff
path: root/mobly/controllers/android_device_lib/fastboot.py
blob: cac08f1d37aca0fcb4bc941d921e77c9d2d8fa7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
from subprocess import Popen, PIPE

from mobly import utils


def exe_cmd(*cmds):
  """Executes commands in a new shell. Directing stderr to PIPE.

  This is fastboot's own exe_cmd because of its peculiar way of writing
  non-error info to stderr.

  Args:
    cmds: A sequence of commands and arguments.

  Returns:
    The output of the command run.

  Raises:
    Exception: An error occurred during the command execution.
  """
  cmd = ' '.join(cmds)
  proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
  (out, err) = proc.communicate()
  ret = proc.returncode
  logging.debug(
      'cmd: %s, stdout: %s, stderr: %s, ret: %s',
      utils.cli_cmd_to_string(cmds),
      out,
      err,
      ret,
  )
  if not err:
    return out
  return err


class FastbootProxy:
  """Proxy class for fastboot.

  For syntactic reasons, the '-' in fastboot commands need to be replaced
  with '_'. Can directly execute fastboot commands on an object:
  >> fb = FastbootProxy(<serial>)
  >> fb.devices() # will return the console output of "fastboot devices".
  """

  def __init__(self, serial=''):
    self.serial = serial
    if serial:
      self.fastboot_str = 'fastboot -s {}'.format(serial)
    else:
      self.fastboot_str = 'fastboot'

  def _exec_fastboot_cmd(self, name, arg_str):
    return exe_cmd(' '.join((self.fastboot_str, name, arg_str)))

  def args(self, *args):
    return exe_cmd(' '.join((self.fastboot_str,) + args))

  def __getattr__(self, name):
    def fastboot_call(*args):
      clean_name = name.replace('_', '-')
      arg_str = ' '.join(str(elem) for elem in args)
      return self._exec_fastboot_cmd(clean_name, arg_str)

    return fastboot_call