Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DO NOT MERGE] compare upstream/master vs. origin/documentation #7

Open
wants to merge 2 commits into
base: master-black-no-comments
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 18 additions & 17 deletions adb/adb_commands.py
Expand Up @@ -7,31 +7,33 @@
from adb import common
from adb import filesync_protocol

try:
file_types = (file, io.IOBase)
except NameError:
file_types = (io.IOBase,)

CLASS = 0xFF

SUBCLASS = 0x42

PROTOCOL = 0x01

DeviceIsAvailable = common.InterfaceMatcher(CLASS, SUBCLASS, PROTOCOL)

try:
from adb.sign_cryptography import CryptographySigner
except ImportError:
pass


class AdbCommands(object):
protocol_handler = adb_protocol.AdbMessage
filesync_handler = filesync_protocol.FilesyncProtocol

def __init__(self):
self.__reset()

def __reset(self):
self.build_props = None
self._handle = None
self._device_state = None
self._handle = None
self._service_connections = {}

def __reset(self):
self.__init__()

def _get_service_connection(
self, service, service_command=None, create=True, timeout_ms=None
):
Expand Down Expand Up @@ -124,7 +126,7 @@ def Install(
cmd.append('"{}"'.format(destination_path))
ret = self.Shell(" ".join(cmd), timeout_ms=timeout_ms)
rm_cmd = ["rm", destination_path]
rmret = self.Shell(" ".join(rm_cmd), timeout_ms=timeout_ms)
self.Shell(" ".join(rm_cmd), timeout_ms=timeout_ms)
return ret

def Uninstall(self, package_name, keep_data=False, timeout_ms=None):
Expand Down Expand Up @@ -178,22 +180,21 @@ def Pull(
dest_file = io.BytesIO()
elif isinstance(dest_file, str):
dest_file = open(dest_file, "wb")
elif isinstance(dest_file, file):
elif isinstance(dest_file, file_types):
pass
else:
raise ValueError("destfile is of unknown type")
raise ValueError("dest_file is of unknown type")
conn = self.protocol_handler.Open(
self._handle, destination=b"sync:", timeout_ms=timeout_ms
)
self.filesync_handler.Pull(conn, device_filename, dest_file, progress_callback)
conn.Close()
if isinstance(dest_file, io.BytesIO):
return dest_file.getvalue()
else:
dest_file.close()
if hasattr(dest_file, "name"):
return os.path.exists(dest_file.name)
return True
dest_file.close()
if hasattr(dest_file, "name"):
return os.path.exists(dest_file.name)
return True

def Stat(self, device_filename):
connection = self.protocol_handler.Open(self._handle, destination=b"sync:")
Expand Down
40 changes: 18 additions & 22 deletions adb/adb_debug.py
Expand Up @@ -81,24 +81,22 @@ def Logcat(device, *options):
def Shell(device, *command):
if command:
return device.StreamingShell(" ".join(command))
else:
terminal_prompt = device.InteractiveShell()
print(terminal_prompt.decode("utf-8"))
while True:
cmd = input("> ")
if not cmd:
continue
elif cmd == "exit":
break
else:
stdout = device.InteractiveShell(
cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True
)
if stdout:
if isinstance(stdout, bytes):
stdout = stdout.decode("utf-8")
print(stdout)
device.Close()
terminal_prompt = device.InteractiveShell()
print(terminal_prompt.decode("utf-8"))
while True:
cmd = input("> ")
if not cmd:
continue
if cmd == "exit":
break
stdout = device.InteractiveShell(
cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True
)
if stdout:
if isinstance(stdout, bytes):
stdout = stdout.decode("utf-8")
print(stdout)
device.Close()


def main():
Expand All @@ -115,8 +113,7 @@ def main():
default=60.0,
metavar="60",
type=int,
help="Seconds to wait for the dialog to be accepted when using "
"authenticated ADB.",
help="Seconds to wait for the dialog to be accepted when using authenticated ADB.",
)
device = common_cli.GetDeviceArguments()
parents = [common, device]
Expand Down Expand Up @@ -148,8 +145,7 @@ def main():
parents,
adb_commands.AdbCommands.Pull,
{
"dest_file": "Filename to write to on the host, if not specified, "
"prints the content to stdout."
"dest_file": "Filename to write to on the host, if not specified, prints the content to stdout."
},
)
common_cli.MakeSubparser(subparsers, parents, adb_commands.AdbCommands.Reboot)
Expand Down
56 changes: 34 additions & 22 deletions adb/adb_protocol.py
Expand Up @@ -8,22 +8,10 @@
VERSION = 0x01000000

AUTH_TOKEN = 1
AUTH_SIGNATURE = 2
AUTH_RSAPUBLICKEY = 3

AUTH_SIGNATURE = 2

def find_backspace_runs(stdout_bytes, start_pos):
first_backspace_pos = stdout_bytes[start_pos:].find(b"\x08")
if first_backspace_pos == -1:
return -1, 0
end_backspace_pos = (start_pos + first_backspace_pos) + 1
while True:
if chr(stdout_bytes[end_backspace_pos]) == "\b":
end_backspace_pos += 1
else:
break
num_backspaces = end_backspace_pos - (start_pos + first_backspace_pos)
return (start_pos + first_backspace_pos), num_backspaces
AUTH_RSAPUBLICKEY = 3


class InvalidCommandError(Exception):
Expand All @@ -42,6 +30,20 @@ class InvalidChecksumError(Exception):
class InterleavedDataError(Exception):


def find_backspace_runs(stdout_bytes, start_pos):
first_backspace_pos = stdout_bytes[start_pos:].find(b"\x08")
if first_backspace_pos == -1:
return -1, 0
end_backspace_pos = (start_pos + first_backspace_pos) + 1
while True:
if chr(stdout_bytes[end_backspace_pos]) == "\b":
end_backspace_pos += 1
else:
break
num_backspaces = end_backspace_pos - (start_pos + first_backspace_pos)
return (start_pos + first_backspace_pos), num_backspaces


def MakeWireIDs(ids):
id_to_wire = {
cmd_id: sum(c << (i * 8) for i, c in enumerate(bytearray(cmd_id)))
Expand Down Expand Up @@ -79,7 +81,11 @@ def Write(self, data):
"Command failed.", okay_data
)
raise InvalidCommandError(
"Expected an OKAY in response to a WRITE, got %s (%s)", cmd, okay_data
"Expected an OKAY in response to a WRITE, got {0} ({1})".format(
cmd, okay_data
),
cmd,
okay_data,
)
return len(data)

Expand All @@ -90,11 +96,13 @@ def ReadUntil(self, *expected_cmds):
cmd, remote_id, local_id, data = AdbMessage.Read(
self.usb, expected_cmds, self.timeout_ms
)
if local_id != 0 and self.local_id != local_id:
if local_id not in (0, self.local_id):
raise InterleavedDataError("We don't support multiple streams...")
if remote_id != 0 and self.remote_id != remote_id:
if remote_id not in (0, self.remote_id):
raise InvalidResponseError(
"Incorrect remote id, expected %s got %s" % (self.remote_id, remote_id)
"Incorrect remote id, expected {0} got {1}".format(
self.remote_id, remote_id
)
)
if cmd == b"WRTE":
self.Okay()
Expand All @@ -112,7 +120,9 @@ def ReadUntilClose(self):
"Command failed.", data
)
raise InvalidCommandError(
"Expected a WRITE or a CLOSE, got %s (%s)", cmd, data
"Expected a WRITE or a CLOSE, got {0} ({1})".format(cmd, data),
cmd,
data,
)
yield data

Expand All @@ -123,7 +133,7 @@ def Close(self):
if cmd == b"FAIL":
raise usb_exceptions.AdbCommandFailureException("Command failed.", data)
raise InvalidCommandError(
"Expected a CLSE response, got %s (%s)", cmd, data
"Expected a CLSE response, got {0} ({1})".format(cmd, data), cmd, data
)


Expand Down Expand Up @@ -217,7 +227,9 @@ def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
actual_checksum = cls.CalculateChecksum(data)
if actual_checksum != data_checksum:
raise InvalidChecksumError(
"Received checksum %s != %s", (actual_checksum, data_checksum)
"Received checksum {0} != {1}".format(
actual_checksum, data_checksum
)
)
else:
data = b""
Expand Down Expand Up @@ -344,7 +356,7 @@ def InteractiveShellCommand(
original_cmd = str(cmd)
cmd += "\r"
cmd = cmd.encode("utf8")
bytes_written = conn.Write(cmd)
conn.Write(cmd)
if delim:
data = b""
while partial_delim not in data:
Expand Down
21 changes: 17 additions & 4 deletions adb/common.py
@@ -1,17 +1,26 @@
import logging
import platform
import re
import select
import socket
import threading
import weakref
import select

import libusb1
import usb1

try:
from libusb1 import LIBUSB_ERROR_NOT_FOUND, LIBUSB_ERROR_TIMEOUT
except ImportError:
LIBUSB_ERROR_NOT_FOUND = "LIBUSB_ERROR_NOT_FOUND"
LIBUSB_ERROR_TIMEOUT = "LIBUSB_ERROR_TIMEOUT"

from adb import usb_exceptions

DEFAULT_TIMEOUT_MS = 10000

SYSFS_PORT_SPLIT_RE = re.compile("[,/:.-]")

_LOG = logging.getLogger("android_usb")


Expand All @@ -26,6 +35,7 @@ def Matcher(device):
for setting in device.iterSettings():
if GetInterface(setting) == interface:
return setting
return None

return Matcher

Expand All @@ -38,6 +48,9 @@ def __init__(self, device, setting, usb_info=None, timeout_ms=None):
self._setting = setting
self._device = device
self._handle = None
self._interface_number = None
self._read_endpoint = None
self._write_endpoint = None
self._usb_info = usb_info or ""
self._timeout_ms = timeout_ms if timeout_ms else DEFAULT_TIMEOUT_MS
self._max_read_packet_len = 0
Expand Down Expand Up @@ -77,7 +90,7 @@ def Open(self):
):
handle.detachKernelDriver(iface_number)
except libusb1.USBError as e:
if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
if e.value == LIBUSB_ERROR_NOT_FOUND:
_LOG.warning("Kernel driver not found for interface: %s.", iface_number)
else:
raise
Expand Down Expand Up @@ -117,7 +130,7 @@ def FlushBuffers(self):
try:
self.BulkRead(self._max_read_packet_len, timeout_ms=10)
except usb_exceptions.ReadFailedError as e:
if e.usb_error.value == libusb1.LIBUSB_ERROR_TIMEOUT:
if e.usb_error.value == LIBUSB_ERROR_TIMEOUT:
break
raise

Expand Down Expand Up @@ -158,7 +171,7 @@ def BulkRead(self, length, timeout_ms=None):
)

def BulkReadAsync(self, length, timeout_ms=None):
return
raise NotImplementedError

@classmethod
def PortPathMatcher(cls, port_path):
Expand Down
31 changes: 16 additions & 15 deletions adb/common_cli.py
Expand Up @@ -49,24 +49,25 @@ def GetCommonArguments():


def _DocToArgs(doc):
m = None
offset = None
in_arg = False
param = None
out = {}
for l in doc.splitlines():
if l.strip() == "Args:":
in_arg = True
elif in_arg:
if not l.strip():
if l.strip() == "Parameters":
offset = len(l.rstrip()) - len(l.strip())
elif offset:
if l.strip() == "-" * len("Parameters"):
continue
if l.strip() in ["Returns", "Yields", "Raises"]:
break
if offset is None:
offset = len(l) - len(l.lstrip())
l = l[offset:]
if l[0] == " " and m:
out[m.group(1)] += " " + l.lstrip()
else:
m = re.match(r"^([a-z_]+): (.+)$", l.strip())
out[m.group(1)] = m.group(2)
if len(l.rstrip()) - len(l.strip()) == offset:
param = l.strip().split()[0]
out[param] = ""
elif l.strip():
if out[param]:
out[param] += " " + l.strip()
else:
out[param] = l.strip()
return out


Expand All @@ -77,7 +78,7 @@ def MakeSubparser(subparsers, parents, method, arguments=None):
name=name, description=help, help=help.rstrip("."), parents=parents
)
subparser.set_defaults(method=method, positional=[])
argspec = inspect.getargspec(method)
argspec = inspect.getfullargspec(method)
offset = len(argspec.args) - len(argspec.defaults or []) - 1
positional = []
for i in range(1, len(argspec.args)):
Expand Down