Skip to content

Commit

Permalink
Documentation and code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffLIrion committed Sep 16, 2019
1 parent 711ea4a commit f5078e8
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 63 deletions.
42 changes: 17 additions & 25 deletions adb/adb_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def _get_service_connection(self, service, service_command=None, create=True, ti
Additional service parameters to append
create : bool
If False, don't create a connection if it does not exist
timeout_ms : TODO, None
timeout_ms : int, None
TODO
Returns
Expand All @@ -159,8 +159,7 @@ def _get_service_connection(self, service, service_command=None, create=True, ti
else:
destination_str = service

connection = self.protocol_handler.Open(
self._handle, destination=destination_str, timeout_ms=timeout_ms)
connection = self.protocol_handler.Open(self._handle, destination=destination_str, timeout_ms=timeout_ms)

self._service_connections.update({service: connection})

Expand Down Expand Up @@ -191,7 +190,7 @@ def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, **
List of AuthSigner subclass instances to be used for authentication. The device can either accept one
of these via the ``Sign`` method, or we will send the result of ``GetPublicKey`` from the first one if the
device doesn't accept any of them.
auth_timeout_ms : TODO
auth_timeout_ms : int
Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The
device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this
should be low to catch such a case as a failure quickly; while in interactive settings it should be high to
Expand All @@ -214,9 +213,7 @@ def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, **
if serial and ':' in serial:
self._handle = common.TcpHandle(serial, timeout_ms=default_timeout_ms)
else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._handle = common.UsbHandle.FindAndOpen(DeviceIsAvailable, port_path=port_path, serial=serial, timeout_ms=default_timeout_ms)

self._Connect(**kwargs)

Expand Down Expand Up @@ -321,7 +318,7 @@ def Install(self, apk_path, destination_dir='', replace_existing=True,
Whether to replace existing application
grant_permissions : bool
If ``True``, grant all permissions to the app specified in its manifest
timeout_ms : TODO, None
timeout_ms : int, None
Expected timeout for pushing and installing.
transfer_progress_callback : TODO, None
callback method that accepts ``filename``, ``bytes_written``, and ``total_bytes`` of APK transfer
Expand Down Expand Up @@ -364,7 +361,7 @@ def Uninstall(self, package_name, keep_data=False, timeout_ms=None):
Package name of target package.
keep_data : bool
Whether to keep the data and cache directories
timeout_ms : TODO, None
timeout_ms : int, None
Expected timeout for pushing and installing.
Returns
Expand Down Expand Up @@ -395,7 +392,7 @@ def Push(self, source_file, device_filename, mtime='0', timeout_ms=None, progres
Destination on the device to write to.
mtime : str
Modification time to set on the file.
timeout_ms : TODO, None
timeout_ms : int, None
Expected timeout for any part of the push.
progress_callback : TODO, None
Callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like
Expand All @@ -408,19 +405,17 @@ def Push(self, source_file, device_filename, mtime='0', timeout_ms=None, progres
if os.path.isdir(source_file):
self.Shell("mkdir " + device_filename)
for f in os.listdir(source_file):
self.Push(os.path.join(source_file, f), device_filename + '/' + f,
progress_callback=progress_callback)
self.Push(os.path.join(source_file, f), device_filename + '/' + f, progress_callback=progress_callback)
return

source_file = open(source_file, "rb")

with source_file:
connection = self.protocol_handler.Open(
self._handle, destination=b'sync:', timeout_ms=timeout_ms)
connection = self.protocol_handler.Open(self._handle, destination=b'sync:', timeout_ms=timeout_ms)
kwargs = {}
if st_mode is not None:
kwargs['st_mode'] = st_mode
self.filesync_handler.Push(connection, source_file, device_filename,
mtime=int(mtime), progress_callback=progress_callback, **kwargs)
self.filesync_handler.Push(connection, source_file, device_filename, mtime=int(mtime), progress_callback=progress_callback, **kwargs)
connection.Close()

def Pull(self, device_filename, dest_file=None, timeout_ms=None, progress_callback=None):
Expand All @@ -432,7 +427,7 @@ def Pull(self, device_filename, dest_file=None, timeout_ms=None, progress_callba
Filename on the device to pull.
dest_file : str, file, io.IOBase, None
If set, a filename or writable file-like object.
timeout_ms : TODO, None
timeout_ms : int, None
Expected timeout for any part of the pull.
progress_callback : TODO, None
Callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like
Expand Down Expand Up @@ -495,8 +490,7 @@ def Stat(self, device_filename):
"""
connection = self.protocol_handler.Open(self._handle, destination=b'sync:')
mode, size, mtime = self.filesync_handler.Stat(
connection, device_filename)
mode, size, mtime = self.filesync_handler.Stat(connection, device_filename)
connection.Close()
return mode, size, mtime

Expand Down Expand Up @@ -593,7 +587,7 @@ def Shell(self, command, timeout_ms=None):
----------
command : TODO
Shell command to run
timeout_ms : TODO, None
timeout_ms : int, None
Maximum time to allow the command to run.
Returns
Expand All @@ -613,7 +607,7 @@ def StreamingShell(self, command, timeout_ms=None):
----------
command : bytes
Command to run on the target.
timeout_ms : TODO, None
timeout_ms : int, None
Maximum time to allow the command to run.
Returns
Expand All @@ -633,7 +627,7 @@ def Logcat(self, options, timeout_ms=None):
----------
options : str
Arguments to pass to ``logcat``
timeout_ms : TODO, None
timeout_ms : int, None
Maximum time to allow the command to run.
Returns
Expand Down Expand Up @@ -669,6 +663,4 @@ def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=Tru
"""
conn = self._get_service_connection(b'shell:')

return self.protocol_handler.InteractiveShellCommand(
conn, cmd=cmd, strip_cmd=strip_cmd,
delim=delim, strip_delim=strip_delim)
return self.protocol_handler.InteractiveShellCommand(conn, cmd=cmd, strip_cmd=strip_cmd, delim=delim, strip_delim=strip_delim)
3 changes: 1 addition & 2 deletions adb/adb_keygen.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,7 @@ def decode_pubkey(public_key):
"""
binary_key_data = base64.b64decode(public_key)
modulus_size_words, n0inv, modulus_bytes, rr_bytes, exponent = \
struct.unpack(ANDROID_RSAPUBLICKEY_STRUCT, binary_key_data)
modulus_size_words, n0inv, modulus_bytes, rr_bytes, exponent = struct.unpack(ANDROID_RSAPUBLICKEY_STRUCT, binary_key_data)
assert modulus_size_words == ANDROID_PUBKEY_MODULUS_SIZE_WORDS
modulus = reversed(modulus_bytes)
rr = reversed(rr_bytes)
Expand Down
19 changes: 8 additions & 11 deletions adb/adb_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,7 @@ def MakeWireIDs(ids):
TODO
"""
id_to_wire = {
cmd_id: sum(c << (i * 8) for i, c in enumerate(bytearray(cmd_id)))
for cmd_id in ids
}
id_to_wire = {cmd_id: sum(c << (i * 8) for i, c in enumerate(bytearray(cmd_id))) for cmd_id in ids}
wire_to_id = {wire: cmd_id for cmd_id, wire in id_to_wire.items()}
return id_to_wire, wire_to_id

Expand Down Expand Up @@ -513,8 +510,7 @@ def Pack(self):
TODO
"""
return struct.pack(self.format, self.command, self.arg0, self.arg1,
len(self.data), self.checksum, self.magic)
return struct.pack(self.format, self.command, self.arg0, self.arg1, len(self.data), self.checksum, self.magic)

@classmethod
def Unpack(cls, message):
Expand Down Expand Up @@ -552,6 +548,7 @@ def Unpack(cls, message):
cmd, arg0, arg1, data_length, data_checksum, unused_magic = struct.unpack(cls.format, message)
except struct.error as e:
raise ValueError('Unable to unpack ADB command.', cls.format, message, e)

return cmd, arg0, arg1, data_length, data_checksum

def Send(self, usb, timeout_ms=None):
Expand Down Expand Up @@ -610,6 +607,7 @@ def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
"""
total_timeout_ms = usb.Timeout(total_timeout_ms)
start = time.time()

while True:
msg = usb.BulkRead(24, timeout_ms)
cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
Expand Down Expand Up @@ -638,6 +636,7 @@ def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
raise InvalidChecksumError('Received checksum {0} != {1}'.format(actual_checksum, data_checksum))
else:
data = b''

return command, arg0, arg1, bytes(data)

@classmethod
Expand Down Expand Up @@ -754,9 +753,7 @@ def Open(cls, usb, destination, timeout_ms=None):
"""
local_id = 1
msg = cls(
command=b'OPEN', arg0=local_id, arg1=0,
data=destination + b'\0')
msg = cls(command=b'OPEN', arg0=local_id, arg1=0, data=destination + b'\0')
msg.Send(usb, timeout_ms)
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'], timeout_ms=timeout_ms)

Expand All @@ -771,8 +768,8 @@ def Open(cls, usb, destination, timeout_ms=None):
return None

if cmd != b'OKAY':
raise InvalidCommandError('Expected a ready response, got {}'.format(cmd),
cmd, (remote_id, their_local_id))
raise InvalidCommandError('Expected a ready response, got {}'.format(cmd), cmd, (remote_id, their_local_id))

return _AdbConnection(usb, local_id, remote_id, timeout_ms)

@classmethod
Expand Down
31 changes: 9 additions & 22 deletions adb/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,16 +370,12 @@ def BulkWrite(self, data, timeout_ms=None):
"""
if self._handle is None:
raise usb_exceptions.WriteFailedError(
'This handle has been closed, probably due to another being opened.',
None)
raise usb_exceptions.WriteFailedError('This handle has been closed, probably due to another being opened.', None)
try:
return self._handle.bulkWrite(
self._write_endpoint, data, timeout=self.Timeout(timeout_ms))
except libusb1.USBError as e:
raise usb_exceptions.WriteFailedError(
'Could not send data to %s (timeout %sms)' % (
self.usb_info, self.Timeout(timeout_ms)), e)
raise usb_exceptions.WriteFailedError('Could not send data to %s (timeout %sms)' % (self.usb_info, self.Timeout(timeout_ms)), e)

def BulkRead(self, length, timeout_ms=None):
"""TODO
Expand Down Expand Up @@ -407,19 +403,14 @@ def BulkRead(self, length, timeout_ms=None):
"""
if self._handle is None:
raise usb_exceptions.ReadFailedError(
'This handle has been closed, probably due to another being opened.',
None)
raise usb_exceptions.ReadFailedError('This handle has been closed, probably due to another being opened.', None)
try:
# python-libusb1 > 1.6 exposes bytearray()s now instead of bytes/str.
# To support older and newer versions, we ensure everything's bytearray()
# from here on out.
return bytearray(self._handle.bulkRead(
self._read_endpoint, length, timeout=self.Timeout(timeout_ms)))
return bytearray(self._handle.bulkRead(self._read_endpoint, length, timeout=self.Timeout(timeout_ms)))
except libusb1.USBError as e:
raise usb_exceptions.ReadFailedError(
'Could not receive data from %s (timeout %sms)' % (
self.usb_info, self.Timeout(timeout_ms)), e)
raise usb_exceptions.ReadFailedError('Could not receive data from %s (timeout %sms)' % (self.usb_info, self.Timeout(timeout_ms)), e)

def BulkReadAsync(self, length, timeout_ms=None):
"""TODO
Expand Down Expand Up @@ -547,8 +538,7 @@ def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
else:
device_matcher = None
usb_info = 'first'
return cls.FindFirst(setting_matcher, device_matcher,
usb_info=usb_info, timeout_ms=timeout_ms)
return cls.FindFirst(setting_matcher, device_matcher, usb_info=usb_info, timeout_ms=timeout_ms)

@classmethod
def FindFirst(cls, setting_matcher, device_matcher=None, **kwargs):
Expand Down Expand Up @@ -672,8 +662,7 @@ def _connect(self):
"""
timeout = self.TimeoutSeconds(self._timeout_ms)
self._connection = socket.create_connection((self.host, self.port),
timeout=timeout)
self._connection = socket.create_connection((self.host, self.port), timeout=timeout)
if timeout:
self._connection.setblocking(0)

Expand Down Expand Up @@ -718,8 +707,7 @@ def BulkWrite(self, data, timeout=None):
_, writeable, _ = select.select([], [self._connection], [], t)
if writeable:
return self._connection.send(data)
msg = 'Sending data to {} timed out after {}s. No data was sent.'.format(
self.serial_number, t)
msg = 'Sending data to {} timed out after {}s. No data was sent.'.format(self.serial_number, t)
raise usb_exceptions.TcpTimeoutException(msg)

def BulkRead(self, numbytes, timeout=None):
Expand Down Expand Up @@ -749,8 +737,7 @@ def BulkRead(self, numbytes, timeout=None):
readable, _, _ = select.select([self._connection], [], [], t)
if readable:
return self._connection.recv(numbytes)
msg = 'Reading from {} timed out (Timeout {}s)'.format(
self._serial_number, t)
msg = 'Reading from {} timed out (Timeout {}s)'.format(self._serial_number, t)
raise usb_exceptions.TcpTimeoutException(msg)

def Timeout(self, timeout_ms):
Expand Down
4 changes: 1 addition & 3 deletions adb/fastboot.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,9 +433,7 @@ def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, ch
self._handle = kwargs['handle']

else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._handle = common.UsbHandle.FindAndOpen(DeviceIsAvailable, port_path=port_path, serial=serial, timeout_ms=default_timeout_ms)

self._protocol = FastbootProtocol(self._handle, chunk_kb)

Expand Down

0 comments on commit f5078e8

Please sign in to comment.