blob: 66ef623fa57127de8f04c0945071815346927b11 [file] [log] [blame]
csmartdalton0262b5c2016-09-19 12:04:56 -07001# Copyright 2016 Google Inc.
2#
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
csmartdaltone4fd0782016-11-09 08:41:23 -08006from __future__ import print_function
csmartdaltond7a9db62016-09-22 05:10:02 -07007import re
csmartdalton0262b5c2016-09-19 12:04:56 -07008import subprocess
csmartdalton310d72c2016-10-18 09:19:50 -07009import sys
csmartdalton0262b5c2016-09-19 12:04:56 -070010
csmartdaltond7a9db62016-09-22 05:10:02 -070011class Adb:
csmartdaltona1151292016-11-09 15:37:48 -050012 def __init__(self, device_serial=None, echo=False):
csmartdaltond7a9db62016-09-22 05:10:02 -070013 self.__invocation = ['adb']
14 if device_serial:
15 self.__invocation.extend(['-s', device_serial])
csmartdaltona1151292016-11-09 15:37:48 -050016 self.__echo = echo
csmartdaltone4fd0782016-11-09 08:41:23 -080017 self.__is_root = None
csmartdalton0262b5c2016-09-19 12:04:56 -070018
csmartdaltond7a9db62016-09-22 05:10:02 -070019 def shell(self, cmd):
csmartdaltona1151292016-11-09 15:37:48 -050020 if self.__echo:
21 self.__echo_shell_cmd(cmd)
22 self.__invoke('shell', cmd)
csmartdaltond7a9db62016-09-22 05:10:02 -070023
24 def check(self, cmd):
csmartdaltona1151292016-11-09 15:37:48 -050025 if self.__echo:
26 self.__echo_shell_cmd(cmd)
csmartdaltond7a9db62016-09-22 05:10:02 -070027 result = subprocess.check_output(self.__invocation + ['shell', cmd])
csmartdaltona1151292016-11-09 15:37:48 -050028 if self.__echo:
29 print(result, file=sys.stderr)
csmartdaltone4fd0782016-11-09 08:41:23 -080030 return result
csmartdaltond7a9db62016-09-22 05:10:02 -070031
csmartdaltone4fd0782016-11-09 08:41:23 -080032 def root(self):
33 if not self.is_root():
csmartdaltona1151292016-11-09 15:37:48 -050034 self.__invoke('root')
35 self.__invoke('wait-for-device')
csmartdaltone4fd0782016-11-09 08:41:23 -080036 self.__is_root = None
37 return self.is_root()
csmartdaltond7a9db62016-09-22 05:10:02 -070038
39 def is_root(self):
csmartdaltone4fd0782016-11-09 08:41:23 -080040 if self.__is_root is None:
41 self.__is_root = ('root' == self.check('whoami').strip())
42 return self.__is_root
csmartdaltond7a9db62016-09-22 05:10:02 -070043
44 def remount(self):
csmartdaltona1151292016-11-09 15:37:48 -050045 self.__invoke('remount')
csmartdaltone4fd0782016-11-09 08:41:23 -080046
csmartdaltona1151292016-11-09 15:37:48 -050047 def __echo_shell_cmd(self, cmd):
csmartdaltone4fd0782016-11-09 08:41:23 -080048 escaped = [re.sub(r'([^a-zA-Z0-9])', r'\\\1', x)
49 for x in cmd.strip().splitlines()]
csmartdaltona1151292016-11-09 15:37:48 -050050 self.__invoke('shell', 'echo', '$(whoami)@$(getprop ro.serialno)$',
51 " '\n>' ".join(escaped))
52
53 def __invoke(self, *args):
54 subprocess.call(self.__invocation + list(args), stdout=sys.stderr)