Skip to content

Commit bb32b6d

Browse files
committed
'documentation' branch: remove comments and apply black formatting
Re-run black_remove_comments.sh Re-run black_remove_comments.sh
1 parent 096cafa commit bb32b6d

12 files changed

+146
-112
lines changed

adb/adb_commands.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,31 +7,33 @@
77
from adb import common
88
from adb import filesync_protocol
99

10+
try:
11+
file_types = (file, io.IOBase)
12+
except NameError:
13+
file_types = (io.IOBase,)
14+
1015
CLASS = 0xFF
16+
1117
SUBCLASS = 0x42
18+
1219
PROTOCOL = 0x01
1320

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

16-
try:
17-
from adb.sign_cryptography import CryptographySigner
18-
except ImportError:
19-
pass
20-
2123

2224
class AdbCommands(object):
2325
protocol_handler = adb_protocol.AdbMessage
2426
filesync_handler = filesync_protocol.FilesyncProtocol
2527

2628
def __init__(self):
27-
self.__reset()
28-
29-
def __reset(self):
3029
self.build_props = None
31-
self._handle = None
3230
self._device_state = None
31+
self._handle = None
3332
self._service_connections = {}
3433

34+
def __reset(self):
35+
self.__init__()
36+
3537
def _get_service_connection(
3638
self, service, service_command=None, create=True, timeout_ms=None
3739
):
@@ -124,7 +126,7 @@ def Install(
124126
cmd.append('"{}"'.format(destination_path))
125127
ret = self.Shell(" ".join(cmd), timeout_ms=timeout_ms)
126128
rm_cmd = ["rm", destination_path]
127-
rmret = self.Shell(" ".join(rm_cmd), timeout_ms=timeout_ms)
129+
self.Shell(" ".join(rm_cmd), timeout_ms=timeout_ms)
128130
return ret
129131

130132
def Uninstall(self, package_name, keep_data=False, timeout_ms=None):
@@ -178,22 +180,21 @@ def Pull(
178180
dest_file = io.BytesIO()
179181
elif isinstance(dest_file, str):
180182
dest_file = open(dest_file, "wb")
181-
elif isinstance(dest_file, file):
183+
elif isinstance(dest_file, file_types):
182184
pass
183185
else:
184-
raise ValueError("destfile is of unknown type")
186+
raise ValueError("dest_file is of unknown type")
185187
conn = self.protocol_handler.Open(
186188
self._handle, destination=b"sync:", timeout_ms=timeout_ms
187189
)
188190
self.filesync_handler.Pull(conn, device_filename, dest_file, progress_callback)
189191
conn.Close()
190192
if isinstance(dest_file, io.BytesIO):
191193
return dest_file.getvalue()
192-
else:
193-
dest_file.close()
194-
if hasattr(dest_file, "name"):
195-
return os.path.exists(dest_file.name)
196-
return True
194+
dest_file.close()
195+
if hasattr(dest_file, "name"):
196+
return os.path.exists(dest_file.name)
197+
return True
197198

198199
def Stat(self, device_filename):
199200
connection = self.protocol_handler.Open(self._handle, destination=b"sync:")

adb/adb_debug.py

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -81,24 +81,23 @@ def Logcat(device, *options):
8181
def Shell(device, *command):
8282
if command:
8383
return device.StreamingShell(" ".join(command))
84-
else:
85-
terminal_prompt = device.InteractiveShell()
86-
print(terminal_prompt.decode("utf-8"))
87-
while True:
88-
cmd = input("> ")
89-
if not cmd:
90-
continue
91-
elif cmd == "exit":
92-
break
93-
else:
94-
stdout = device.InteractiveShell(
95-
cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True
96-
)
97-
if stdout:
98-
if isinstance(stdout, bytes):
99-
stdout = stdout.decode("utf-8")
100-
print(stdout)
101-
device.Close()
84+
terminal_prompt = device.InteractiveShell()
85+
print(terminal_prompt.decode("utf-8"))
86+
while True:
87+
cmd = input("> ")
88+
if not cmd:
89+
continue
90+
elif cmd == "exit":
91+
break
92+
else:
93+
stdout = device.InteractiveShell(
94+
cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True
95+
)
96+
if stdout:
97+
if isinstance(stdout, bytes):
98+
stdout = stdout.decode("utf-8")
99+
print(stdout)
100+
device.Close()
102101

103102

104103
def main():
@@ -115,8 +114,7 @@ def main():
115114
default=60.0,
116115
metavar="60",
117116
type=int,
118-
help="Seconds to wait for the dialog to be accepted when using "
119-
"authenticated ADB.",
117+
help="Seconds to wait for the dialog to be accepted when using authenticated ADB.",
120118
)
121119
device = common_cli.GetDeviceArguments()
122120
parents = [common, device]
@@ -148,8 +146,7 @@ def main():
148146
parents,
149147
adb_commands.AdbCommands.Pull,
150148
{
151-
"dest_file": "Filename to write to on the host, if not specified, "
152-
"prints the content to stdout."
149+
"dest_file": "Filename to write to on the host, if not specified, prints the content to stdout."
153150
},
154151
)
155152
common_cli.MakeSubparser(subparsers, parents, adb_commands.AdbCommands.Reboot)

adb/adb_protocol.py

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,10 @@
88
VERSION = 0x01000000
99

1010
AUTH_TOKEN = 1
11-
AUTH_SIGNATURE = 2
12-
AUTH_RSAPUBLICKEY = 3
1311

12+
AUTH_SIGNATURE = 2
1413

15-
def find_backspace_runs(stdout_bytes, start_pos):
16-
first_backspace_pos = stdout_bytes[start_pos:].find(b"\x08")
17-
if first_backspace_pos == -1:
18-
return -1, 0
19-
end_backspace_pos = (start_pos + first_backspace_pos) + 1
20-
while True:
21-
if chr(stdout_bytes[end_backspace_pos]) == "\b":
22-
end_backspace_pos += 1
23-
else:
24-
break
25-
num_backspaces = end_backspace_pos - (start_pos + first_backspace_pos)
26-
return (start_pos + first_backspace_pos), num_backspaces
14+
AUTH_RSAPUBLICKEY = 3
2715

2816

2917
class InvalidCommandError(Exception):
@@ -42,6 +30,20 @@ class InvalidChecksumError(Exception):
4230
class InterleavedDataError(Exception):
4331

4432

33+
def find_backspace_runs(stdout_bytes, start_pos):
34+
first_backspace_pos = stdout_bytes[start_pos:].find(b"\x08")
35+
if first_backspace_pos == -1:
36+
return -1, 0
37+
end_backspace_pos = (start_pos + first_backspace_pos) + 1
38+
while True:
39+
if chr(stdout_bytes[end_backspace_pos]) == "\b":
40+
end_backspace_pos += 1
41+
else:
42+
break
43+
num_backspaces = end_backspace_pos - (start_pos + first_backspace_pos)
44+
return (start_pos + first_backspace_pos), num_backspaces
45+
46+
4547
def MakeWireIDs(ids):
4648
id_to_wire = {
4749
cmd_id: sum(c << (i * 8) for i, c in enumerate(bytearray(cmd_id)))
@@ -79,7 +81,11 @@ def Write(self, data):
7981
"Command failed.", okay_data
8082
)
8183
raise InvalidCommandError(
82-
"Expected an OKAY in response to a WRITE, got %s (%s)", cmd, okay_data
84+
"Expected an OKAY in response to a WRITE, got {0} ({1})".format(
85+
cmd, okay_data
86+
),
87+
cmd,
88+
okay_data,
8389
)
8490
return len(data)
8591

@@ -90,11 +96,13 @@ def ReadUntil(self, *expected_cmds):
9096
cmd, remote_id, local_id, data = AdbMessage.Read(
9197
self.usb, expected_cmds, self.timeout_ms
9298
)
93-
if local_id != 0 and self.local_id != local_id:
99+
if local_id not in (0, self.local_id):
94100
raise InterleavedDataError("We don't support multiple streams...")
95-
if remote_id != 0 and self.remote_id != remote_id:
101+
if remote_id not in (0, self.remote_id):
96102
raise InvalidResponseError(
97-
"Incorrect remote id, expected %s got %s" % (self.remote_id, remote_id)
103+
"Incorrect remote id, expected {0} got {1}".format(
104+
self.remote_id, remote_id
105+
)
98106
)
99107
if cmd == b"WRTE":
100108
self.Okay()
@@ -112,7 +120,9 @@ def ReadUntilClose(self):
112120
"Command failed.", data
113121
)
114122
raise InvalidCommandError(
115-
"Expected a WRITE or a CLOSE, got %s (%s)", cmd, data
123+
"Expected a WRITE or a CLOSE, got {0} ({1})".format(cmd, data),
124+
cmd,
125+
data,
116126
)
117127
yield data
118128

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

129139

@@ -217,7 +227,9 @@ def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
217227
actual_checksum = cls.CalculateChecksum(data)
218228
if actual_checksum != data_checksum:
219229
raise InvalidChecksumError(
220-
"Received checksum %s != %s", (actual_checksum, data_checksum)
230+
"Received checksum {0} != {1}".format(
231+
actual_checksum, data_checksum
232+
)
221233
)
222234
else:
223235
data = b""
@@ -344,7 +356,7 @@ def InteractiveShellCommand(
344356
original_cmd = str(cmd)
345357
cmd += "\r"
346358
cmd = cmd.encode("utf8")
347-
bytes_written = conn.Write(cmd)
359+
conn.Write(cmd)
348360
if delim:
349361
data = b""
350362
while partial_delim not in data:

adb/common.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
import logging
22
import platform
3+
import re
4+
import select
35
import socket
46
import threading
57
import weakref
6-
import select
78

89
import libusb1
910
import usb1
1011

12+
try:
13+
from libusb1 import LIBUSB_ERROR_NOT_FOUND, LIBUSB_ERROR_TIMEOUT
14+
except ImportError:
15+
LIBUSB_ERROR_NOT_FOUND = "LIBUSB_ERROR_NOT_FOUND"
16+
LIBUSB_ERROR_TIMEOUT = "LIBUSB_ERROR_TIMEOUT"
17+
1118
from adb import usb_exceptions
1219

1320
DEFAULT_TIMEOUT_MS = 10000
1421

22+
SYSFS_PORT_SPLIT_RE = re.compile("[,/:.-]")
23+
1524
_LOG = logging.getLogger("android_usb")
1625

1726

@@ -26,6 +35,7 @@ def Matcher(device):
2635
for setting in device.iterSettings():
2736
if GetInterface(setting) == interface:
2837
return setting
38+
return None
2939

3040
return Matcher
3141

@@ -38,6 +48,9 @@ def __init__(self, device, setting, usb_info=None, timeout_ms=None):
3848
self._setting = setting
3949
self._device = device
4050
self._handle = None
51+
self._interface_number = None
52+
self._read_endpoint = None
53+
self._write_endpoint = None
4154
self._usb_info = usb_info or ""
4255
self._timeout_ms = timeout_ms if timeout_ms else DEFAULT_TIMEOUT_MS
4356
self._max_read_packet_len = 0
@@ -77,7 +90,7 @@ def Open(self):
7790
):
7891
handle.detachKernelDriver(iface_number)
7992
except libusb1.USBError as e:
80-
if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
93+
if e.value == LIBUSB_ERROR_NOT_FOUND:
8194
_LOG.warning("Kernel driver not found for interface: %s.", iface_number)
8295
else:
8396
raise
@@ -117,7 +130,7 @@ def FlushBuffers(self):
117130
try:
118131
self.BulkRead(self._max_read_packet_len, timeout_ms=10)
119132
except usb_exceptions.ReadFailedError as e:
120-
if e.usb_error.value == libusb1.LIBUSB_ERROR_TIMEOUT:
133+
if e.usb_error.value == LIBUSB_ERROR_TIMEOUT:
121134
break
122135
raise
123136

@@ -158,7 +171,7 @@ def BulkRead(self, length, timeout_ms=None):
158171
)
159172

160173
def BulkReadAsync(self, length, timeout_ms=None):
161-
return
174+
raise NotImplementedError
162175

163176
@classmethod
164177
def PortPathMatcher(cls, port_path):

adb/common_cli.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -49,24 +49,25 @@ def GetCommonArguments():
4949

5050

5151
def _DocToArgs(doc):
52-
m = None
5352
offset = None
54-
in_arg = False
53+
param = None
5554
out = {}
5655
for l in doc.splitlines():
57-
if l.strip() == "Args:":
58-
in_arg = True
59-
elif in_arg:
60-
if not l.strip():
56+
if l.strip() == "Parameters":
57+
offset = len(l.rstrip()) - len(l.strip())
58+
elif offset:
59+
if l.strip() == "-" * len("Parameters"):
60+
continue
61+
if l.strip() in ["Returns", "Yields", "Raises"]:
6162
break
62-
if offset is None:
63-
offset = len(l) - len(l.lstrip())
64-
l = l[offset:]
65-
if l[0] == " " and m:
66-
out[m.group(1)] += " " + l.lstrip()
67-
else:
68-
m = re.match(r"^([a-z_]+): (.+)$", l.strip())
69-
out[m.group(1)] = m.group(2)
63+
if len(l.rstrip()) - len(l.strip()) == offset:
64+
param = l.strip().split()[0]
65+
out[param] = ""
66+
elif l.strip():
67+
if out[param]:
68+
out[param] += " " + l.strip()
69+
else:
70+
out[param] = l.strip()
7071
return out
7172

7273

@@ -77,7 +78,7 @@ def MakeSubparser(subparsers, parents, method, arguments=None):
7778
name=name, description=help, help=help.rstrip("."), parents=parents
7879
)
7980
subparser.set_defaults(method=method, positional=[])
80-
argspec = inspect.getargspec(method)
81+
argspec = inspect.getfullargspec(method)
8182
offset = len(argspec.args) - len(argspec.defaults or []) - 1
8283
positional = []
8384
for i in range(1, len(argspec.args)):

0 commit comments

Comments
 (0)