lustro-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lustro_cli/__init__.py +29 -0
- lustro_cli/cli.py +2460 -0
- lustro_cli/client.py +434 -0
- lustro_cli/discovery.py +1033 -0
- lustro_cli/exitcodes.py +25 -0
- lustro_cli/mcp.py +867 -0
- lustro_cli/wire/__init__.py +62 -0
- lustro_cli/wire/_schema.json +97 -0
- lustro_cli/wire/cursor-envelope.schema.json +28 -0
- lustro_cli/wire/error-envelope.schema.json +46 -0
- lustro_cli/wire/golden/cursor-delta.json +91 -0
- lustro_cli/wire/golden/cursor-reset.json +65 -0
- lustro_cli/wire/golden/cursor-unchanged.json +15 -0
- lustro_cli/wire/golden/error-envelope.json +7 -0
- lustro_cli/wire/golden/export-har-websocket.json +148 -0
- lustro_cli/wire/golden/export-har.json +359 -0
- lustro_cli/wire/golden/logs-delta.json +44 -0
- lustro_cli/wire/golden/logs-reset.json +73 -0
- lustro_cli/wire/golden/logs-unchanged.json +9 -0
- lustro_cli/wire/golden/meta.json +12 -0
- lustro_cli/wire/golden/prefs-delta.json +58 -0
- lustro_cli/wire/golden/prefs-files.json +64 -0
- lustro_cli/wire/golden/prefs-reset.json +58 -0
- lustro_cli/wire/golden/prefs-unchanged.json +4 -0
- lustro_cli/wire/golden/rules-list.json +44 -0
- lustro_cli/wire/golden/screen-tree-views.json +596 -0
- lustro_cli/wire/golden/screen-tree.json +689 -0
- lustro_cli/wire/golden/send-result.json +7 -0
- lustro_cli/wire/golden/senders-list.json +6 -0
- lustro_cli/wire/golden/sqlite-databases.json +37 -0
- lustro_cli/wire/golden/sqlite-exec.json +4 -0
- lustro_cli/wire/golden/sqlite-query.json +109 -0
- lustro_cli/wire/golden/sqlite-rows.json +109 -0
- lustro_cli/wire/golden/sqlite-schema.json +98 -0
- lustro_cli/wire/golden/sqlite-tables.json +57 -0
- lustro_cli/wire/golden/stream-delta.json +48 -0
- lustro_cli/wire/golden/stream-reset.json +66 -0
- lustro_cli/wire/golden/stream-unchanged.json +4 -0
- lustro_cli/wire/golden/transaction-image.json +43 -0
- lustro_cli/wire/golden/transaction.json +41 -0
- lustro_cli/wire/golden/websocket.json +37 -0
- lustro_cli/wire/golden/websockets-reset.json +89 -0
- lustro_cli/wire/golden/work-events.json +152 -0
- lustro_cli/wire/golden/work-item.json +118 -0
- lustro_cli/wire/golden/work-items.json +129 -0
- lustro_cli/wire/golden/work-metrics.json +40 -0
- lustro_cli/wire/logs.openapi.json +622 -0
- lustro_cli/wire/meta.schema.json +47 -0
- lustro_cli/wire/network.openapi.json +2458 -0
- lustro_cli/wire/pagination.schema.json +20 -0
- lustro_cli/wire/prefs.openapi.json +699 -0
- lustro_cli/wire/screen.openapi.json +512 -0
- lustro_cli/wire/sqlite.openapi.json +1233 -0
- lustro_cli/wire/stream-envelope.schema.json +33 -0
- lustro_cli/wire/sync.py +80 -0
- lustro_cli/wire/work.openapi.json +1188 -0
- lustro_cli-0.1.0.dist-info/METADATA +585 -0
- lustro_cli-0.1.0.dist-info/RECORD +60 -0
- lustro_cli-0.1.0.dist-info/WHEEL +4 -0
- lustro_cli-0.1.0.dist-info/entry_points.txt +3 -0
lustro_cli/cli.py
ADDED
|
@@ -0,0 +1,2460 @@
|
|
|
1
|
+
"""``lustro`` command-line interface.
|
|
2
|
+
|
|
3
|
+
Argparse-based dispatch over the Lustro HTTP wire protocol. Every subcommand
|
|
4
|
+
maps to a route in ``network.openapi.json`` or ``screen.openapi.json``, or a framework route
|
|
5
|
+
(``/api/v1/_meta``, ``/api/v1/_schema``, ``/api/v1/<id>/_schema``), except
|
|
6
|
+
``api``, which sends a request to any route, ``ready``, which waits until the
|
|
7
|
+
server answers, and ``mcp``, which runs an MCP server whose tools call these
|
|
8
|
+
routes (see ``mcp.py``). Each cause of a failure has its own exit code (see
|
|
9
|
+
``exitcodes.py``).
|
|
10
|
+
|
|
11
|
+
The output is small by default, because agents read all of it: ``net list``
|
|
12
|
+
prints the newest rows only, a row shows a short id, ``net get`` cuts long
|
|
13
|
+
bodies, and JSON is compact unless stdout is a terminal.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
import urllib.parse
|
|
27
|
+
import webbrowser
|
|
28
|
+
from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple
|
|
29
|
+
|
|
30
|
+
from . import PROTOCOL_VERSION, REVISION, __version__, exitcodes, wire
|
|
31
|
+
from .client import CursorState, LustroClient, LustroError
|
|
32
|
+
from .discovery import (
|
|
33
|
+
DEFAULT_HOST,
|
|
34
|
+
DEFAULT_PORT,
|
|
35
|
+
LOOPBACK_HOSTS,
|
|
36
|
+
DiscoveryError,
|
|
37
|
+
Endpoint,
|
|
38
|
+
PortHeld,
|
|
39
|
+
TokenGuard,
|
|
40
|
+
TokenWithheld,
|
|
41
|
+
device_problem,
|
|
42
|
+
diagnose,
|
|
43
|
+
forwarded_ports,
|
|
44
|
+
package_paths,
|
|
45
|
+
resolve,
|
|
46
|
+
token_from_prefs,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
API_ROOT = "/api/v1/"
|
|
50
|
+
META = API_ROOT + "_meta"
|
|
51
|
+
NETWORK = "/api/v1/network"
|
|
52
|
+
TRANSACTIONS = NETWORK + "/transactions"
|
|
53
|
+
EXPORT = TRANSACTIONS + "/_/export"
|
|
54
|
+
WEBSOCKETS = NETWORK + "/websockets"
|
|
55
|
+
|
|
56
|
+
# The flags that every command takes, before or after its name, and their values
|
|
57
|
+
# when they are not given. See _global_options for why main() sets these.
|
|
58
|
+
GLOBAL_DEFAULTS: Dict[str, Any] = {
|
|
59
|
+
"host": None,
|
|
60
|
+
"port": None,
|
|
61
|
+
"token": None,
|
|
62
|
+
"device": None,
|
|
63
|
+
"package": None,
|
|
64
|
+
"json": False,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
DEFAULT_LAST = 50
|
|
68
|
+
DEFAULT_MAX_BODY = 2048
|
|
69
|
+
SHORT_ID_LENGTH = 8
|
|
70
|
+
# How many of the matches an ambiguous id prints.
|
|
71
|
+
AMBIGUOUS_ROWS = 10
|
|
72
|
+
ID_HELP = "a transaction id, or its start, such as the short id of a row"
|
|
73
|
+
WS_ID_HELP = "a connection id, or its start, such as the short id of a row"
|
|
74
|
+
# More than a log can hold, so that the server sends all of it.
|
|
75
|
+
ALL_EVENTS = 1_000_000
|
|
76
|
+
# How many ids one export request names. The server takes a request line and
|
|
77
|
+
# headers of up to 8 KB, and a full id is 36 characters.
|
|
78
|
+
EXPORT_BATCH = 50
|
|
79
|
+
|
|
80
|
+
# The Lustro runtime makes each transaction id with UUID.randomUUID(). An id of
|
|
81
|
+
# this shape goes to the server as it is, without the list request that a
|
|
82
|
+
# shorter one needs.
|
|
83
|
+
_FULL_ID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class UsageError(Exception):
|
|
87
|
+
"""A request that the command can't carry out as given. main() prints it and exits 2."""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ForwardFailed(LustroError):
|
|
91
|
+
"""No adb forward reaches the app's port, and adb could make none."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
DEFAULT_READY_TIMEOUT = 30.0
|
|
95
|
+
# How long `ready` waits between two tries.
|
|
96
|
+
READY_INTERVAL = 1.0
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ── output helpers ────────────────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _dumps(obj: Any, *, indent: bool) -> str:
|
|
103
|
+
if indent:
|
|
104
|
+
return json.dumps(obj, indent=2, ensure_ascii=False)
|
|
105
|
+
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _emit(obj: Any, *, raw_json: bool) -> None:
|
|
109
|
+
"""Print a result. ``--json`` output, and any dict or list, prints as JSON:
|
|
110
|
+
indented for a person at a terminal, compact for a pipe or a file."""
|
|
111
|
+
if raw_json or isinstance(obj, (dict, list)):
|
|
112
|
+
print(_dumps(obj, indent=sys.stdout.isatty()))
|
|
113
|
+
elif obj is None:
|
|
114
|
+
pass
|
|
115
|
+
else:
|
|
116
|
+
print(obj)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _seconds(value: float) -> str:
|
|
120
|
+
return "{:g}".format(value)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ── transactions: rows, filters, fields ───────────────────────────────────────
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _is_complete(tx: dict) -> bool:
|
|
127
|
+
"""Whether the request is over: its response is complete, or it failed.
|
|
128
|
+
|
|
129
|
+
``completedAt`` says so from protocol 1.2; the other two cover a 1.1 server.
|
|
130
|
+
"""
|
|
131
|
+
return tx.get("completedAt") is not None or bool(tx.get("error")) or tx.get("responseComplete") is True
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _is_error(tx: dict) -> bool:
|
|
135
|
+
status = tx.get("statusCode")
|
|
136
|
+
return bool(tx.get("error")) or (isinstance(status, int) and status >= 400)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _short_id_length(items: Iterable[Any]) -> int:
|
|
140
|
+
"""How many characters of each id the rows show: 8, or more when two of the
|
|
141
|
+
listed ids start with the same 8, so that each row's id names one transaction."""
|
|
142
|
+
ids = sorted({tx["id"] for tx in items if isinstance(tx, dict) and isinstance(tx.get("id"), str)})
|
|
143
|
+
length = SHORT_ID_LENGTH
|
|
144
|
+
# In sorted order, the two ids with the longest common start are neighbours.
|
|
145
|
+
for first, second in zip(ids, ids[1:]):
|
|
146
|
+
length = max(length, _common_start_length(first, second) + 1)
|
|
147
|
+
return length
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _common_start_length(first: str, second: str) -> int:
|
|
151
|
+
"""How many characters at the start of the two strings are the same.
|
|
152
|
+
|
|
153
|
+
The ids are not paths, so os.path.commonpath does not apply, and Python 3.15
|
|
154
|
+
deprecates os.path.commonprefix.
|
|
155
|
+
"""
|
|
156
|
+
length = 0
|
|
157
|
+
for a, b in zip(first, second):
|
|
158
|
+
if a != b:
|
|
159
|
+
break
|
|
160
|
+
length += 1
|
|
161
|
+
return length
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _format_row(tx: dict, id_length: Optional[int] = None, *, update: bool = False) -> str:
|
|
165
|
+
"""One table row. The id keeps its first ``id_length`` characters, or all of them."""
|
|
166
|
+
status = tx.get("statusCode")
|
|
167
|
+
if tx.get("error"):
|
|
168
|
+
status_str = "ERR"
|
|
169
|
+
elif status is not None:
|
|
170
|
+
status_str = str(status)
|
|
171
|
+
else:
|
|
172
|
+
status_str = "..."
|
|
173
|
+
duration = tx.get("durationMs")
|
|
174
|
+
flags = ""
|
|
175
|
+
if tx.get("isMocked"):
|
|
176
|
+
flags += " [mock]"
|
|
177
|
+
# Mock rules and the throttle act on OkHttp requests; a request another adapter captured says which.
|
|
178
|
+
if tx.get("source") not in (None, "okhttp"):
|
|
179
|
+
flags += " [{}]".format(tx["source"])
|
|
180
|
+
if tx.get("throttledMs"):
|
|
181
|
+
flags += " [throttled {}ms]".format(tx["throttledMs"])
|
|
182
|
+
if tx.get("finalUrl"):
|
|
183
|
+
flags += " [-> {}]".format(tx["finalUrl"])
|
|
184
|
+
if status is not None and not _is_complete(tx):
|
|
185
|
+
flags += " [streaming]"
|
|
186
|
+
if update:
|
|
187
|
+
flags += " [update]"
|
|
188
|
+
return "{id} {ts:>12} {method:<6} {status:>4} {duration:>7} {url}{flags}".format(
|
|
189
|
+
id=str(tx.get("id", ""))[:id_length],
|
|
190
|
+
ts=tx.get("timestamp", ""),
|
|
191
|
+
method=tx.get("method", ""),
|
|
192
|
+
status=status_str,
|
|
193
|
+
duration="-" if duration is None else "{}ms".format(duration),
|
|
194
|
+
url=tx.get("url", ""),
|
|
195
|
+
flags=flags,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _prints_json_lines(args: argparse.Namespace) -> bool:
|
|
200
|
+
return args.json or args.fields is not None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _print_transaction(tx: dict, args: argparse.Namespace, id_length: int, *, update: bool = False) -> None:
|
|
204
|
+
"""Print one transaction as a table row with a short id, or as one compact
|
|
205
|
+
JSON line with the full id. A JSON line has no update mark: the later line
|
|
206
|
+
for an id replaces the earlier one."""
|
|
207
|
+
if _prints_json_lines(args):
|
|
208
|
+
if args.fields is not None:
|
|
209
|
+
tx = {name: tx.get(name) for name in args.fields}
|
|
210
|
+
print(_dumps(tx, indent=False))
|
|
211
|
+
else:
|
|
212
|
+
print(_format_row(tx, id_length, update=update))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _matches(tx: dict, args: argparse.Namespace) -> bool:
|
|
216
|
+
"""Whether a transaction passes the client-side filters. ``--search`` ran on the server."""
|
|
217
|
+
if args.method is not None and str(tx.get("method", "")).upper() != args.method.upper():
|
|
218
|
+
return False
|
|
219
|
+
if args.url is not None and args.url.lower() not in str(tx.get("url", "")).lower():
|
|
220
|
+
return False
|
|
221
|
+
if args.status is not None:
|
|
222
|
+
low, high = args.status
|
|
223
|
+
status = tx.get("statusCode")
|
|
224
|
+
if not isinstance(status, int) or not low <= status <= high:
|
|
225
|
+
return False
|
|
226
|
+
return not args.errors or _is_error(tx)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _check_fields(
|
|
230
|
+
args: argparse.Namespace, items: Iterable[Any], *, component: str = "Transaction", noun: str = "transactions"
|
|
231
|
+
) -> None:
|
|
232
|
+
"""Reject a ``--fields`` key that no item has, so that a typo such as
|
|
233
|
+
``status`` for ``statusCode`` fails instead of printing null on every line.
|
|
234
|
+
A key that the server sends but this CLI doesn't know yet passes."""
|
|
235
|
+
if args.fields is None:
|
|
236
|
+
return
|
|
237
|
+
known = list(wire.load_openapi()["components"]["schemas"][component]["properties"])
|
|
238
|
+
seen = set(known)
|
|
239
|
+
for tx in items:
|
|
240
|
+
for key in tx if isinstance(tx, dict) else ():
|
|
241
|
+
if key not in seen:
|
|
242
|
+
seen.add(key)
|
|
243
|
+
known.append(key)
|
|
244
|
+
unknown = [name for name in args.fields if name not in seen]
|
|
245
|
+
if unknown:
|
|
246
|
+
raise UsageError(
|
|
247
|
+
"--fields: {} have no {}. They have: {}".format(noun, ", ".join(unknown), ",".join(known))
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _search_params(args: argparse.Namespace) -> Dict[str, Optional[str]]:
|
|
252
|
+
"""The search and regex parameters of --search and --regex."""
|
|
253
|
+
if args.regex:
|
|
254
|
+
return {"search": args.search, "regex": "true"}
|
|
255
|
+
return {"search": args.search}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _is_search_error(exc: LustroError) -> bool:
|
|
259
|
+
"""Whether the app rejected the search: a query that can't run, or one that took too long. Polling again won't help."""
|
|
260
|
+
return exc.status == 400 and exc.field == "search"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _note_if_paused(data: Any, what: str = "new requests are not listed") -> None:
|
|
264
|
+
state = data.get("state") if isinstance(data, dict) else None
|
|
265
|
+
if isinstance(state, dict) and state.get("paused") is True:
|
|
266
|
+
print(
|
|
267
|
+
"note: capture is paused, so {}; `lustro net pause` resumes it".format(what),
|
|
268
|
+
file=sys.stderr,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _list_items(data: Any) -> List[dict]:
|
|
273
|
+
items = data.get("items") if isinstance(data, dict) else None
|
|
274
|
+
return [tx for tx in items or [] if isinstance(tx, dict)]
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _cut_bodies(tx: dict, limit: int, more: str = "lustro net body {id} {direction}") -> None:
|
|
278
|
+
"""Cut each text body to ``limit`` UTF-8 bytes, and end it with a marker that
|
|
279
|
+
says how many bytes are left out and which command prints them: ``more``,
|
|
280
|
+
with the transaction's ``{id}`` and the body's ``{direction}``."""
|
|
281
|
+
for direction in ("request", "response"):
|
|
282
|
+
key = direction + "Body"
|
|
283
|
+
text = tx.get(key)
|
|
284
|
+
if not isinstance(text, str):
|
|
285
|
+
continue
|
|
286
|
+
data = text.encode("utf-8", "surrogatepass")
|
|
287
|
+
if len(data) <= limit:
|
|
288
|
+
continue
|
|
289
|
+
cut = limit
|
|
290
|
+
# Keep whole characters: move back to the first byte of the one at the cut.
|
|
291
|
+
while cut > 0 and (data[cut] & 0xC0) == 0x80:
|
|
292
|
+
cut -= 1
|
|
293
|
+
tx[key] = "{}[... {} more bytes: {}]".format(
|
|
294
|
+
data[:cut].decode("utf-8", "surrogatepass"),
|
|
295
|
+
len(data) - cut,
|
|
296
|
+
more.format(id=tx.get("id"), direction=direction),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _resolve_id(client: LustroClient, given: str) -> str:
|
|
301
|
+
"""The full id of the transaction that ``given`` names: the id itself, or
|
|
302
|
+
the start of only one id, such as the short id of a row. A start costs one
|
|
303
|
+
list request, because the wire routes take only a full id."""
|
|
304
|
+
if not given:
|
|
305
|
+
raise UsageError("expected a transaction id, or the start of one")
|
|
306
|
+
return _resolve_ids(client, [given])[0]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _resolve_ids(client: LustroClient, given: List[str]) -> List[str]:
|
|
310
|
+
"""The full id of each transaction in ``given``, as _resolve_id finds it.
|
|
311
|
+
One list request covers every start."""
|
|
312
|
+
items: Optional[List[dict]] = None
|
|
313
|
+
resolved = []
|
|
314
|
+
for start in given:
|
|
315
|
+
if _FULL_ID.fullmatch(start):
|
|
316
|
+
resolved.append(start)
|
|
317
|
+
continue
|
|
318
|
+
if items is None:
|
|
319
|
+
items = _list_items(client.get(TRANSACTIONS))
|
|
320
|
+
resolved.append(_match_id(items, start))
|
|
321
|
+
return resolved
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _match_id(
|
|
325
|
+
items: List[dict], given: str, *, noun: str = "transaction", list_command: str = "lustro net list", row=None
|
|
326
|
+
) -> str:
|
|
327
|
+
matches = [tx for tx in items if isinstance(tx.get("id"), str) and tx["id"].startswith(given)]
|
|
328
|
+
# An id of another shape can also be the start of a longer one.
|
|
329
|
+
if any(tx["id"] == given for tx in matches):
|
|
330
|
+
return given
|
|
331
|
+
if len(matches) == 1:
|
|
332
|
+
return matches[0]["id"]
|
|
333
|
+
if not matches:
|
|
334
|
+
raise LustroError(
|
|
335
|
+
"not_found",
|
|
336
|
+
"no {} id starts with {}".format(noun, given),
|
|
337
|
+
hint="`{}` prints the {}s that the app has now".format(list_command, noun),
|
|
338
|
+
)
|
|
339
|
+
rows = [(row or _format_row)(tx) for tx in matches[:AMBIGUOUS_ROWS]]
|
|
340
|
+
if len(matches) > AMBIGUOUS_ROWS:
|
|
341
|
+
rows.append("and {} more".format(len(matches) - AMBIGUOUS_ROWS))
|
|
342
|
+
raise UsageError(
|
|
343
|
+
"{} {} ids start with {}. Give more characters of the id:\n {}".format(
|
|
344
|
+
len(matches), noun, given, "\n ".join(rows)
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# ── WebSockets: rows ───────────────────────────────────────────────────────────
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _ws_state(connection: dict) -> str:
|
|
353
|
+
"""The state as a row shows it: with the close code, or with what made the socket fail."""
|
|
354
|
+
state = str(connection.get("state", ""))
|
|
355
|
+
if state == "closed" and connection.get("closeCode") is not None:
|
|
356
|
+
return "closed {}".format(connection["closeCode"])
|
|
357
|
+
if state == "failed":
|
|
358
|
+
if connection.get("canceled"):
|
|
359
|
+
return "canceled"
|
|
360
|
+
status = connection.get("statusCode")
|
|
361
|
+
if isinstance(status, int) and status != 101:
|
|
362
|
+
return "failed {}".format(status)
|
|
363
|
+
return state
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _format_ws_row(connection: dict, id_length: Optional[int] = None) -> str:
|
|
367
|
+
"""One table row. The id keeps its first ``id_length`` characters, or all of them."""
|
|
368
|
+
return "{id} {ts:>12} {state:<11} sent={sent} received={received} {url}".format(
|
|
369
|
+
id=str(connection.get("id", ""))[:id_length],
|
|
370
|
+
ts=connection.get("timestamp", ""),
|
|
371
|
+
state=_ws_state(connection),
|
|
372
|
+
sent=connection.get("sentCount", 0),
|
|
373
|
+
received=connection.get("receivedCount", 0),
|
|
374
|
+
url=connection.get("url", ""),
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _one_line(text: str) -> str:
|
|
379
|
+
return " ".join(text.split())
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _format_event_row(event: dict, connection_id: str) -> str:
|
|
383
|
+
"""One row of a connection's log. A message shows its direction, type, size,
|
|
384
|
+
and the start of its payload; a lifecycle event shows what happened."""
|
|
385
|
+
head = "{seq:>5} {ts:>12} ".format(seq=event.get("seq", ""), ts=event.get("timestamp", ""))
|
|
386
|
+
kind = event.get("kind")
|
|
387
|
+
sent = event.get("direction") == "sent"
|
|
388
|
+
if kind != "message":
|
|
389
|
+
parts = [str(kind)]
|
|
390
|
+
if kind == "close":
|
|
391
|
+
parts.append("sent" if sent else "received")
|
|
392
|
+
for key in ("code", "statusCode", "reason", "error"):
|
|
393
|
+
if event.get(key) not in (None, ""):
|
|
394
|
+
parts.append(str(event[key]))
|
|
395
|
+
if event.get("enqueued") is False:
|
|
396
|
+
parts.append("[refused]")
|
|
397
|
+
return head + "-- " + " ".join(parts)
|
|
398
|
+
if event.get("type") == "binary":
|
|
399
|
+
text = str(event.get("hexPreview", ""))
|
|
400
|
+
else:
|
|
401
|
+
text = _one_line(str(event.get("preview", "")))
|
|
402
|
+
if event.get("previewComplete") is False:
|
|
403
|
+
# The same marker as a cut body: what is left out, and the command that prints it.
|
|
404
|
+
more = int(event.get("payloadBytes") or 0) - len(str(event.get("preview", "")).encode("utf-8", "surrogatepass"))
|
|
405
|
+
text += "[... {} more bytes: lustro net ws payload {} {}]".format(
|
|
406
|
+
max(more, 0), connection_id[:SHORT_ID_LENGTH], event.get("seq")
|
|
407
|
+
)
|
|
408
|
+
flags = ""
|
|
409
|
+
if event.get("enqueued") is False:
|
|
410
|
+
flags += " [not sent]"
|
|
411
|
+
if event.get("truncated"):
|
|
412
|
+
flags += " [truncated]"
|
|
413
|
+
if event.get("stored") is False:
|
|
414
|
+
flags += " [not stored]"
|
|
415
|
+
return head + "{arrow} {type:<6} {size:>9} {text}{flags}".format(
|
|
416
|
+
arrow="->" if sent else "<-",
|
|
417
|
+
type=event.get("type", ""),
|
|
418
|
+
size="{}B".format(event.get("payloadBytes", 0)),
|
|
419
|
+
text=text,
|
|
420
|
+
flags=flags,
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _resolve_ws_id(client: LustroClient, given: str) -> str:
|
|
425
|
+
"""The full id of the connection that ``given`` names, as _resolve_id finds a transaction's."""
|
|
426
|
+
if not given:
|
|
427
|
+
raise UsageError("expected a connection id, or the start of one")
|
|
428
|
+
if _FULL_ID.fullmatch(given):
|
|
429
|
+
return given
|
|
430
|
+
return _match_id(
|
|
431
|
+
_list_items(client.get(WEBSOCKETS)),
|
|
432
|
+
given,
|
|
433
|
+
noun="connection",
|
|
434
|
+
list_command="lustro net ws list",
|
|
435
|
+
row=_format_ws_row,
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
# ── argument types ─────────────────────────────────────────────────────────────
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _status_range(value: str) -> Tuple[int, int]:
|
|
443
|
+
"""``--status``: a code such as 404, or a class such as 4xx."""
|
|
444
|
+
text = value.strip().lower()
|
|
445
|
+
if re.fullmatch(r"[1-5]xx", text):
|
|
446
|
+
low = int(text[0]) * 100
|
|
447
|
+
return low, low + 99
|
|
448
|
+
if re.fullmatch(r"[1-5][0-9][0-9]", text):
|
|
449
|
+
return int(text), int(text)
|
|
450
|
+
raise argparse.ArgumentTypeError("expected a status code such as 404, or a class such as 4xx")
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _id_list(value: str) -> List[str]:
|
|
454
|
+
ids = [part.strip() for part in value.split(",") if part.strip()]
|
|
455
|
+
if not ids:
|
|
456
|
+
raise argparse.ArgumentTypeError("expected transaction ids, or their starts, separated by commas")
|
|
457
|
+
return ids
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _field_names(value: str) -> List[str]:
|
|
461
|
+
names = [name.strip() for name in value.split(",") if name.strip()]
|
|
462
|
+
if not names:
|
|
463
|
+
raise argparse.ArgumentTypeError("expected keys separated by commas, such as id,statusCode,url")
|
|
464
|
+
return names
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _whole_number(minimum: int):
|
|
468
|
+
def parse(value: str) -> int:
|
|
469
|
+
try:
|
|
470
|
+
number = int(value)
|
|
471
|
+
except ValueError:
|
|
472
|
+
number = minimum - 1
|
|
473
|
+
if number < minimum:
|
|
474
|
+
raise argparse.ArgumentTypeError("expected a whole number of {} or more".format(minimum))
|
|
475
|
+
return number
|
|
476
|
+
|
|
477
|
+
return parse
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _port_number(value: str) -> int:
|
|
481
|
+
try:
|
|
482
|
+
number = int(value)
|
|
483
|
+
except ValueError:
|
|
484
|
+
number = -1
|
|
485
|
+
if not 0 <= number <= 65535:
|
|
486
|
+
raise argparse.ArgumentTypeError("expected a port number from 0 to 65535")
|
|
487
|
+
return number
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _positive_seconds(value: str) -> float:
|
|
491
|
+
try:
|
|
492
|
+
seconds = float(value)
|
|
493
|
+
except ValueError:
|
|
494
|
+
seconds = 0.0
|
|
495
|
+
if not (seconds > 0 and math.isfinite(seconds)):
|
|
496
|
+
raise argparse.ArgumentTypeError("expected a number of seconds greater than 0")
|
|
497
|
+
return seconds
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
_HTTP_METHOD = re.compile(r"[A-Za-z]+")
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _http_method(value: str) -> str:
|
|
504
|
+
if not _HTTP_METHOD.fullmatch(value):
|
|
505
|
+
raise argparse.ArgumentTypeError("expected an HTTP method such as GET or POST, got {!r}".format(value))
|
|
506
|
+
return value.upper()
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _param_pair(value: str) -> Tuple[str, str]:
|
|
510
|
+
key, sep, val = value.partition("=")
|
|
511
|
+
if not sep or not key:
|
|
512
|
+
raise argparse.ArgumentTypeError("expected KEY=VALUE, such as level=W, got {!r}".format(value))
|
|
513
|
+
return key, val
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
# ── client construction (discovery) ───────────────────────────────────────────
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _build_endpoint(args: argparse.Namespace, *, check_app: bool = True) -> Endpoint:
|
|
520
|
+
"""The app's endpoint: from the flags, $LUSTRO_TOKEN, and the LustroToken line.
|
|
521
|
+
Without a token, it raises the cause that adb finds, unless ``check_app`` is false."""
|
|
522
|
+
return resolve(
|
|
523
|
+
host=args.host,
|
|
524
|
+
port=args.port,
|
|
525
|
+
token=args.token,
|
|
526
|
+
device=args.device,
|
|
527
|
+
package=getattr(args, "package", None),
|
|
528
|
+
check_app=check_app,
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _token_was_discovered(args: argparse.Namespace) -> bool:
|
|
533
|
+
return args.token is None and not os.environ.get("LUSTRO_TOKEN")
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _with_current_token(args: argparse.Namespace, endpoint: Endpoint) -> Endpoint:
|
|
537
|
+
"""The endpoint with the current token of the app in the foreground, from its prefs,
|
|
538
|
+
when that differs from a discovered one, and that app's server listens on the
|
|
539
|
+
endpoint's port (see :func:`token_from_prefs`). The ready line in the log is from an
|
|
540
|
+
earlier install when the device dropped the new one. The browser gets no second try,
|
|
541
|
+
so ``open`` checks before it prints the URL. With --package, discovery read the token
|
|
542
|
+
from the app's prefs, or could not read them."""
|
|
543
|
+
if not _token_was_discovered(args) or getattr(args, "package", None):
|
|
544
|
+
return endpoint
|
|
545
|
+
current = token_from_prefs(args.device, None, endpoint)
|
|
546
|
+
return endpoint._replace(token=current) if current and current != endpoint.token else endpoint
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _build_client(args: argparse.Namespace, *, check_app: bool = True) -> LustroClient:
|
|
550
|
+
return _client_through_forward(args, check_app=check_app)[0]
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _client_through_forward(
|
|
554
|
+
args: argparse.Namespace, *, check_app: bool = True
|
|
555
|
+
) -> Tuple[LustroClient, Optional[int]]:
|
|
556
|
+
"""The client of :func:`_build_client`, and the app's port on the device when the
|
|
557
|
+
client connects to it through an adb forward, else ``None``."""
|
|
558
|
+
endpoint = _build_endpoint(args, check_app=check_app)
|
|
559
|
+
# The host and the port of the device, which the checks of a discovered token compare.
|
|
560
|
+
found = endpoint
|
|
561
|
+
device_port = None
|
|
562
|
+
# The app's port is on the device. Without --port, connect through an adb
|
|
563
|
+
# forward to it on the selected device, and make one when there is none: the
|
|
564
|
+
# same port number on the computer can be another device's forward.
|
|
565
|
+
if args.port is None and endpoint.host in LOOPBACK_HOSTS:
|
|
566
|
+
local_port = _client_local_port(endpoint.port, args.device)
|
|
567
|
+
if local_port is not None:
|
|
568
|
+
device_port = endpoint.port
|
|
569
|
+
endpoint = endpoint._replace(host=DEFAULT_HOST, port=endpoint.port if local_port is None else local_port)
|
|
570
|
+
# A token from the ready line is stale when the app was installed again and
|
|
571
|
+
# the device dropped the new line. On a 401, the client tries the app's prefs.
|
|
572
|
+
discovered = _token_was_discovered(args)
|
|
573
|
+
package = getattr(args, "package", None)
|
|
574
|
+
guard = TokenGuard(found, args.device) if found.owner is not None else None
|
|
575
|
+
refresh = None
|
|
576
|
+
if guard is not None:
|
|
577
|
+
refresh = lambda: guard.token_from_prefs(package) # noqa: E731
|
|
578
|
+
elif discovered:
|
|
579
|
+
refresh = lambda: token_from_prefs(args.device, package) # noqa: E731
|
|
580
|
+
client = LustroClient(
|
|
581
|
+
endpoint.base_url, endpoint.token, refresh_token=refresh, on_warning=_print_warning, guard=guard
|
|
582
|
+
)
|
|
583
|
+
return client, device_port
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _cause_from_adb(args: argparse.Namespace) -> Optional[DiscoveryError]:
|
|
587
|
+
"""The cause that adb finds for a server that does not answer, such as an app that
|
|
588
|
+
is not running or a build without the Lustro runtime, or ``None``.
|
|
589
|
+
|
|
590
|
+
Not when --host names a host that the CLI reaches without adb, such as a device
|
|
591
|
+
on the LAN, and not when --port names the local port without --device or
|
|
592
|
+
--package, because the server can then be on this computer: adb finds nothing
|
|
593
|
+
about those. --device and --package say that the app is on a device, also with
|
|
594
|
+
--port, such as the local port of a script's own forward. That command does not
|
|
595
|
+
need adb to select the device, so more than one device with none selected says
|
|
596
|
+
nothing about the app.
|
|
597
|
+
"""
|
|
598
|
+
if args.host is not None and args.host not in LOOPBACK_HOSTS:
|
|
599
|
+
return None
|
|
600
|
+
if args.port is not None and not (args.device or args.package):
|
|
601
|
+
return None
|
|
602
|
+
cause = diagnose(args.device, args.package, adb_required=False)
|
|
603
|
+
if cause is not None and cause.exit_code == exitcodes.USAGE and args.port is not None:
|
|
604
|
+
return None
|
|
605
|
+
return cause
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def failure(args: argparse.Namespace, exc: Exception, *, ready_timeout: Optional[float] = None) -> Tuple[int, str]:
|
|
609
|
+
"""The exit code and the message of a command that failed with ``exc``.
|
|
610
|
+
|
|
611
|
+
A connection that fails gets the cause that adb finds, as :func:`_cause_from_adb`
|
|
612
|
+
describes, and so does a discovered token that the CLI did not send, because no server
|
|
613
|
+
of its app listens on the port, and a ``401`` for a token that discovery found: the
|
|
614
|
+
prefs or the log line can name a port where the app no longer listens. When another
|
|
615
|
+
app holds the port, the message names that app after the cause, and exits 6 without
|
|
616
|
+
one: right after the app starts, another app's server can still hold the port. A
|
|
617
|
+
forward that adb can't make gets only the device's cause, such as more than one
|
|
618
|
+
device: the app's state does not stop a forward. ``ready`` passes its
|
|
619
|
+
``ready_timeout``, and its message does not say that ``ready`` waits.
|
|
620
|
+
"""
|
|
621
|
+
if isinstance(exc, UsageError):
|
|
622
|
+
return exitcodes.USAGE, str(exc)
|
|
623
|
+
if isinstance(exc, DiscoveryError):
|
|
624
|
+
return exc.exit_code, str(exc)
|
|
625
|
+
if isinstance(exc, ForwardFailed):
|
|
626
|
+
cause = device_problem(args.device)
|
|
627
|
+
return (exitcodes.NOT_REACHABLE, str(exc)) if cause is None else (cause.exit_code, str(cause))
|
|
628
|
+
if isinstance(exc, LustroError):
|
|
629
|
+
if isinstance(exc, PortHeld):
|
|
630
|
+
held = exc.describe(waits=ready_timeout is None)
|
|
631
|
+
cause = _cause_from_adb(args)
|
|
632
|
+
if cause is None:
|
|
633
|
+
return exitcodes.NOT_REACHABLE, held
|
|
634
|
+
return cause.exit_code, "{} {}".format(cause, held[0].upper() + held[1:])
|
|
635
|
+
if exc.error == "connection_failed" or isinstance(exc, TokenWithheld):
|
|
636
|
+
cause = _cause_from_adb(args)
|
|
637
|
+
return (exitcodes.NOT_REACHABLE, str(exc)) if cause is None else (cause.exit_code, str(cause))
|
|
638
|
+
if exc.status == 401 and _token_was_discovered(args):
|
|
639
|
+
cause = _cause_from_adb(args)
|
|
640
|
+
if cause is not None:
|
|
641
|
+
return cause.exit_code, "{} The server on the app's port answered: {}".format(cause, exc)
|
|
642
|
+
# A search that the app rejects is a usage error, like a bad flag.
|
|
643
|
+
return (exitcodes.USAGE if _is_search_error(exc) else exitcodes.ERROR), str(exc)
|
|
644
|
+
raise exc
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _version_tuple(version: Any) -> Optional[Tuple[int, ...]]:
|
|
648
|
+
parts = str(version).split(".")
|
|
649
|
+
return tuple(int(part) for part in parts) if all(part.isdigit() for part in parts) else None
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def newer_protocol_warning(meta: Any) -> Optional[str]:
|
|
653
|
+
"""A warning when the app's ``protocolVersion`` in ``_meta`` is newer than the one
|
|
654
|
+
this CLI implements: the CLI then lacks what the newer protocol adds."""
|
|
655
|
+
app = meta.get("protocolVersion") if isinstance(meta, dict) else None
|
|
656
|
+
app_version = _version_tuple(app)
|
|
657
|
+
ours = _version_tuple(PROTOCOL_VERSION)
|
|
658
|
+
if app_version is None or ours is None or app_version <= ours:
|
|
659
|
+
return None
|
|
660
|
+
return (
|
|
661
|
+
"the app uses wire protocol {}, and lustro {} implements {}: update the CLI to get what the newer "
|
|
662
|
+
"protocol adds".format(app, __version__, PROTOCOL_VERSION)
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _warn_if_newer_protocol(meta: Any) -> None:
|
|
667
|
+
warning = newer_protocol_warning(meta)
|
|
668
|
+
if warning:
|
|
669
|
+
_print_warning(warning)
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
class Needs(NamedTuple):
|
|
673
|
+
"""The version that an option needs: of the wire protocol, or of the plugin tab ``tab``,
|
|
674
|
+
whose routes have a version of their own, ``tabs[].version`` in ``_meta``."""
|
|
675
|
+
|
|
676
|
+
version: str
|
|
677
|
+
tab: Optional[str] = None
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
# The options and MCP arguments that an app on an older wire protocol, or with an older
|
|
681
|
+
# version of a plugin tab, ignores, with the version that added each. The app answers 200
|
|
682
|
+
# without them, so the command would succeed with a wrong result: a mock rule that
|
|
683
|
+
# answers instead of failing, a text search in place of a regex, the whole log in place
|
|
684
|
+
# of a time range. A command that uses one reads _meta first, and refuses to run against
|
|
685
|
+
# an older app. An option of a route that an older app does not have needs no entry:
|
|
686
|
+
# that app answers 404.
|
|
687
|
+
OPTION_PROTOCOLS: Dict[Tuple[str, str], Needs] = {
|
|
688
|
+
("send", "--sender"): Needs("1.7"),
|
|
689
|
+
("net list", "--regex"): Needs("1.8"),
|
|
690
|
+
("net poll", "--regex"): Needs("1.8"),
|
|
691
|
+
("net wait", "--regex"): Needs("1.8"),
|
|
692
|
+
("net ws events", "--regex"): Needs("1.8"),
|
|
693
|
+
("mock add", "--failure"): Needs("1.12"),
|
|
694
|
+
("mock sync", "failure"): Needs("1.12"),
|
|
695
|
+
# MCP tools.
|
|
696
|
+
("list_requests", "regex"): Needs("1.8"),
|
|
697
|
+
("add_mock_rule", "failure"): Needs("1.12"),
|
|
698
|
+
("read_logs", "from_ms"): Needs("1.1", tab="logs"),
|
|
699
|
+
("read_logs", "to_ms"): Needs("1.1", tab="logs"),
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
# From this revision, the app names each query parameter that a route does not declare
|
|
703
|
+
# in a Lustro-Warning header.
|
|
704
|
+
UNKNOWN_PARAMETER_WARNINGS = "1.15"
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _older(version: Any, needed: str) -> Optional[str]:
|
|
708
|
+
"""``version``, the app's, when it is older than ``needed``, else None. A version that
|
|
709
|
+
the CLI can't compare, or none, is not older."""
|
|
710
|
+
app_version = _version_tuple(version)
|
|
711
|
+
needed_version = _version_tuple(needed)
|
|
712
|
+
if version is None or app_version is None or needed_version is None or app_version >= needed_version:
|
|
713
|
+
return None
|
|
714
|
+
return str(version)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def _app_version(meta: Any, tab: Optional[str]) -> Any:
|
|
718
|
+
"""The app's ``protocolVersion``, or the version of its Lustro plugin tab ``tab``, from
|
|
719
|
+
``_meta``."""
|
|
720
|
+
if not isinstance(meta, dict):
|
|
721
|
+
return None
|
|
722
|
+
protocol = meta.get("protocolVersion")
|
|
723
|
+
if tab is None:
|
|
724
|
+
return protocol
|
|
725
|
+
tabs = meta.get("tabs")
|
|
726
|
+
for entry in tabs if isinstance(tabs, list) else ():
|
|
727
|
+
if isinstance(entry, dict) and entry.get("id") == tab:
|
|
728
|
+
# A plugin tab reports a version of its own from the change that also gave the
|
|
729
|
+
# Logs tab its time range. Before it, _meta gave each tab the protocolVersion,
|
|
730
|
+
# and the tab had the routes of its first version.
|
|
731
|
+
return "1.0" if entry.get("version") == protocol else entry.get("version")
|
|
732
|
+
# No such tab: the request gets the app's 404.
|
|
733
|
+
return None
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def require_protocol(client: LustroClient, command: str, *options: str, hint: Optional[str] = None) -> None:
|
|
737
|
+
"""Raise when the app is older than the version that added one of ``options`` of
|
|
738
|
+
``command`` (see OPTION_PROTOCOLS). Costs one ``_meta`` request."""
|
|
739
|
+
meta = client.get(META)
|
|
740
|
+
for option in options:
|
|
741
|
+
needs = OPTION_PROTOCOLS[(command, option)]
|
|
742
|
+
app = _older(_app_version(meta, needs.tab), needs.version)
|
|
743
|
+
if app is None:
|
|
744
|
+
continue
|
|
745
|
+
# With the other options that have the same need, so that one error names them all.
|
|
746
|
+
same = [name for name in options if OPTION_PROTOCOLS[(command, name)] == needs]
|
|
747
|
+
names = " and ".join(same)
|
|
748
|
+
verb, pronoun = ("need", "them") if len(same) > 1 else ("needs", "it")
|
|
749
|
+
if needs.tab is None:
|
|
750
|
+
needed = "wire protocol {}, and the app uses {}".format(needs.version, app)
|
|
751
|
+
else:
|
|
752
|
+
needed = "version {} of the {} tab, and the app's is {}".format(needs.version, needs.tab, app)
|
|
753
|
+
raise LustroError(
|
|
754
|
+
"protocol_too_old",
|
|
755
|
+
"{} {} {}, which ignores {}".format(names, verb, needed, pronoun),
|
|
756
|
+
hint=hint or "update Lustro in the app, or leave out {}".format(names),
|
|
757
|
+
)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def unwarned_parameters_note(client: LustroClient, schema_command: str) -> Optional[str]:
|
|
761
|
+
"""A note for a request with query parameters to an app that does not warn about a
|
|
762
|
+
parameter that the route does not declare, or None. Costs one ``_meta`` request."""
|
|
763
|
+
app = _older(_app_version(client.get(META), None), UNKNOWN_PARAMETER_WARNINGS)
|
|
764
|
+
if app is None:
|
|
765
|
+
return None
|
|
766
|
+
return (
|
|
767
|
+
"the app uses wire protocol {}, so it does not warn about a query parameter that the route does not "
|
|
768
|
+
"declare (from {}), and the route ignores it: {} lists the parameters of each route".format(
|
|
769
|
+
app, UNKNOWN_PARAMETER_WARNINGS, schema_command
|
|
770
|
+
)
|
|
771
|
+
)
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
_printed_warnings: Set[str] = set()
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def _print_warning(warning: str) -> None:
|
|
778
|
+
"""Prints a warning from the app on stderr, once: a command that polls gets it each time."""
|
|
779
|
+
if warning not in _printed_warnings:
|
|
780
|
+
_printed_warnings.add(warning)
|
|
781
|
+
print("warning: {}".format(warning), file=sys.stderr)
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
# ── adb helpers ────────────────────────────────────────────────────────────────
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def _adb_forward(local_port: int, device_port: int, device: Optional[str]) -> Tuple[int, Optional[str]]:
|
|
788
|
+
"""Run ``adb forward --no-rebind tcp:<local_port> tcp:<device_port>``. Returns
|
|
789
|
+
the local port, which adb chooses when ``local_port`` is 0, and the error, or
|
|
790
|
+
None when the forward works. Raises FileNotFoundError when adb isn't installed.
|
|
791
|
+
|
|
792
|
+
--no-rebind keeps adb from taking over a local port that another device's
|
|
793
|
+
forward holds."""
|
|
794
|
+
cmd = ["adb"]
|
|
795
|
+
if device:
|
|
796
|
+
cmd += ["-s", device]
|
|
797
|
+
cmd += ["forward", "--no-rebind", "tcp:{}".format(local_port), "tcp:{}".format(device_port)]
|
|
798
|
+
try:
|
|
799
|
+
proc = subprocess.run(
|
|
800
|
+
# stdin=DEVNULL: for `lustro mcp`, the CLI's stdin carries the client's messages.
|
|
801
|
+
cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, timeout=10
|
|
802
|
+
)
|
|
803
|
+
except FileNotFoundError:
|
|
804
|
+
raise
|
|
805
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
806
|
+
return local_port, str(exc)
|
|
807
|
+
if proc.returncode != 0:
|
|
808
|
+
return local_port, (
|
|
809
|
+
proc.stderr.decode("utf-8", "replace").strip() or "adb exited with status {}".format(proc.returncode)
|
|
810
|
+
)
|
|
811
|
+
if local_port == 0:
|
|
812
|
+
chosen = proc.stdout.decode("utf-8", "replace").strip()
|
|
813
|
+
if not chosen.isdigit():
|
|
814
|
+
return 0, "adb did not print the local port that it chose: {!r}".format(chosen)
|
|
815
|
+
return int(chosen), None
|
|
816
|
+
return local_port, None
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def _forward_to_app(
|
|
820
|
+
device_port: int, device: Optional[str], *, same_port_first: bool = False
|
|
821
|
+
) -> Tuple[int, Optional[str]]:
|
|
822
|
+
"""The local port of a forward to the app's ``device_port`` on the selected
|
|
823
|
+
device: the first one there is, else a new one on a free port that adb chooses.
|
|
824
|
+
Returns the error of the last forward when none works. Raises FileNotFoundError
|
|
825
|
+
when adb isn't installed.
|
|
826
|
+
|
|
827
|
+
A new forward stays until adb restarts, so it takes its local port from any
|
|
828
|
+
tool that binds the port later, such as a proxy or a development server on
|
|
829
|
+
8080. Only ``open``, whose URL is for a person, prefers the same port number
|
|
830
|
+
(``same_port_first``): a forward on it, else a new one on it, and only then
|
|
831
|
+
the first forward there is. The console keeps its state in the browser for
|
|
832
|
+
each origin, which includes the port, so the URL must not change after an
|
|
833
|
+
earlier command made a forward on a port that adb chose. A script finds the
|
|
834
|
+
forward in ``adb forward --list``."""
|
|
835
|
+
forwarded = forwarded_ports(device_port, device)
|
|
836
|
+
if same_port_first:
|
|
837
|
+
if device_port in forwarded:
|
|
838
|
+
return device_port, None
|
|
839
|
+
local_port, err = _adb_forward(device_port, device_port, device)
|
|
840
|
+
if not err:
|
|
841
|
+
return local_port, None
|
|
842
|
+
if forwarded:
|
|
843
|
+
return forwarded[0], None
|
|
844
|
+
return _adb_forward(0, device_port, device)
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
def _no_forward_error(device_port: int, err: str) -> str:
|
|
848
|
+
"""The error of a command that found no forward to the app's ``device_port``
|
|
849
|
+
and could make none: ``err`` is from the last attempt, on a free port."""
|
|
850
|
+
return "no adb forward reaches the app's port {}: adb forward tcp:0 tcp:{} failed: {}".format(
|
|
851
|
+
device_port, device_port, err
|
|
852
|
+
)
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
_DEVICE_HINT = "Pass --device SERIAL when more than one device is connected."
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def _client_local_port(device_port: int, device: Optional[str]) -> Optional[int]:
|
|
859
|
+
"""The local port of the adb forward that a command connects through, for the
|
|
860
|
+
app's ``device_port``, or ``None`` without adb: there is then no device to forward
|
|
861
|
+
to, and the server is on this computer."""
|
|
862
|
+
try:
|
|
863
|
+
local_port, err = _forward_to_app(device_port, device)
|
|
864
|
+
except FileNotFoundError:
|
|
865
|
+
return None
|
|
866
|
+
if err:
|
|
867
|
+
raise ForwardFailed(
|
|
868
|
+
"connection_failed",
|
|
869
|
+
_no_forward_error(device_port, err),
|
|
870
|
+
hint=(
|
|
871
|
+
_DEVICE_HINT + " For a server on this computer, or a forward that adb does not list, "
|
|
872
|
+
"pass --port N: the CLI then connects to local port N and makes no forward."
|
|
873
|
+
),
|
|
874
|
+
)
|
|
875
|
+
return local_port
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def _forward_local_port(args: argparse.Namespace, device_port: int) -> Optional[int]:
|
|
879
|
+
"""Choose the local port for the console URL, and forward it to the app's
|
|
880
|
+
``device_port``. Returns the local port, or None after it prints why the
|
|
881
|
+
forward failed."""
|
|
882
|
+
if args.no_forward:
|
|
883
|
+
if args.local_port == 0:
|
|
884
|
+
raise UsageError("--local-port 0 lets adb choose the port, so it can't go with --no-forward")
|
|
885
|
+
return device_port if args.local_port is None else args.local_port
|
|
886
|
+
try:
|
|
887
|
+
if args.local_port is None:
|
|
888
|
+
local_port, err = _forward_to_app(device_port, args.device, same_port_first=True)
|
|
889
|
+
else:
|
|
890
|
+
# --local-port 0 keeps an existing forward to the app.
|
|
891
|
+
forwarded = forwarded_ports(device_port, args.device)
|
|
892
|
+
local_port = args.local_port or (forwarded[0] if forwarded else 0)
|
|
893
|
+
# adb forward --no-rebind fails for a forward that is there already.
|
|
894
|
+
if local_port in forwarded:
|
|
895
|
+
return local_port
|
|
896
|
+
local_port, err = _adb_forward(local_port, device_port, args.device)
|
|
897
|
+
except FileNotFoundError:
|
|
898
|
+
if args.local_port is not None:
|
|
899
|
+
print("error: adb is not installed, so --local-port can't forward a port", file=sys.stderr)
|
|
900
|
+
return None
|
|
901
|
+
# Without adb there is no device to forward to: the server is local.
|
|
902
|
+
print("warning: adb is not installed, so the port was not forwarded", file=sys.stderr)
|
|
903
|
+
return device_port
|
|
904
|
+
if err and args.local_port is None:
|
|
905
|
+
print("error: {}".format(_no_forward_error(device_port, err)), file=sys.stderr)
|
|
906
|
+
print(
|
|
907
|
+
" hint: {} Use --no-forward when you forward the port yourself.".format(_DEVICE_HINT),
|
|
908
|
+
file=sys.stderr,
|
|
909
|
+
)
|
|
910
|
+
return None
|
|
911
|
+
if err:
|
|
912
|
+
# The URL would reach whatever holds the local port, not the app.
|
|
913
|
+
print("error: adb forward tcp:{} tcp:{} failed: {}".format(local_port, device_port, err), file=sys.stderr)
|
|
914
|
+
if local_port:
|
|
915
|
+
print(
|
|
916
|
+
" hint: the console URL would not reach the app. If local port {} is taken, pass "
|
|
917
|
+
"--local-port 0 to let adb choose a free port, or --local-port N. Use --no-forward when "
|
|
918
|
+
"you forward the port yourself.".format(local_port),
|
|
919
|
+
file=sys.stderr,
|
|
920
|
+
)
|
|
921
|
+
return None
|
|
922
|
+
return local_port
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
# ── command implementations ────────────────────────────────────────────────────
|
|
926
|
+
|
|
927
|
+
|
|
928
|
+
def cmd_open(args: argparse.Namespace) -> int:
|
|
929
|
+
"""Discover token+endpoint, forward a local port to the app, print/open the browser URL.
|
|
930
|
+
A discovered token goes into the URL only when its app's server listens on the port."""
|
|
931
|
+
endpoint = _build_endpoint(args)
|
|
932
|
+
if endpoint.owner is not None:
|
|
933
|
+
TokenGuard(endpoint, args.device)()
|
|
934
|
+
endpoint = _with_current_token(args, endpoint)
|
|
935
|
+
browser_host = endpoint.host
|
|
936
|
+
port = endpoint.port
|
|
937
|
+
# A LAN host reaches the device without a forward, so only a loopback URL needs one.
|
|
938
|
+
if endpoint.host in LOOPBACK_HOSTS:
|
|
939
|
+
# The browser uses the local end of the forward, whatever host the app binds on the device.
|
|
940
|
+
browser_host = "localhost"
|
|
941
|
+
port = _forward_local_port(args, endpoint.port)
|
|
942
|
+
if port is None:
|
|
943
|
+
return 1
|
|
944
|
+
|
|
945
|
+
# Percent-encode the token so special chars (#, &, %, =) can't corrupt the fragment.
|
|
946
|
+
encoded_token = urllib.parse.quote(endpoint.token, safe="")
|
|
947
|
+
url = "{}://{}:{}/#lustro_token={}".format(
|
|
948
|
+
endpoint.scheme, browser_host, port, encoded_token
|
|
949
|
+
)
|
|
950
|
+
if args.json:
|
|
951
|
+
_emit({"url": url, "token": endpoint.token, "host": browser_host, "port": port}, raw_json=True)
|
|
952
|
+
else:
|
|
953
|
+
print(url)
|
|
954
|
+
if not args.print_only:
|
|
955
|
+
try:
|
|
956
|
+
webbrowser.open(url)
|
|
957
|
+
except Exception: # pragma: no cover - environment dependent
|
|
958
|
+
pass
|
|
959
|
+
return 0
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
def cmd_meta(args: argparse.Namespace) -> int:
|
|
963
|
+
client = _build_client(args)
|
|
964
|
+
meta = client.get(META)
|
|
965
|
+
_warn_if_newer_protocol(meta)
|
|
966
|
+
_emit(meta, raw_json=args.json)
|
|
967
|
+
return 0
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def _package_manager_answers(args: argparse.Namespace) -> bool:
|
|
971
|
+
"""Whether the device's package manager answers about the package of --package,
|
|
972
|
+
or adb has nothing to say about the app, as for a --host on the LAN."""
|
|
973
|
+
if args.host is not None and args.host not in LOOPBACK_HOSTS:
|
|
974
|
+
return True
|
|
975
|
+
return package_paths(args.package, args.device) is not None
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
def cmd_ready(args: argparse.Namespace) -> int:
|
|
979
|
+
"""Wait until the app's server answers ``GET _meta``, print the endpoint, and exit 0.
|
|
980
|
+
At the timeout, print the cause, from adb, and exit with its code.
|
|
981
|
+
|
|
982
|
+
Each try runs discovery again, because the app writes its endpoint only when it
|
|
983
|
+
starts, and the one of an earlier start names a port that does not answer yet.
|
|
984
|
+
The adb checks of the cause run at the end. With --package, they also run once
|
|
985
|
+
after the first try that fails, again on each try until adb reaches the device
|
|
986
|
+
and its package manager answers, and an app that
|
|
987
|
+
is not installed, or a build without the runtime, ends the wait at once: the
|
|
988
|
+
installed APK does not change while ``ready`` waits. Without --package, the app is the one in the foreground,
|
|
989
|
+
which changes while the app starts. An error response that a new try can't
|
|
990
|
+
change, such as a 401 for a token from --token or LUSTRO_TOKEN, ends the wait.
|
|
991
|
+
A 401 for a token that discovery found does not, because the prefs keep the token
|
|
992
|
+
of the app's last process until the new process writes its own. Another app that
|
|
993
|
+
listens on the port does not either: the CLI does not send it the token, and right
|
|
994
|
+
after the app starts, another app with Lustro on the same port can still listen
|
|
995
|
+
there. At the timeout, the message names that app.
|
|
996
|
+
"""
|
|
997
|
+
deadline = time.monotonic() + args.timeout
|
|
998
|
+
checked_early = not args.package
|
|
999
|
+
while True:
|
|
1000
|
+
try:
|
|
1001
|
+
client, device_port = _client_through_forward(args, check_app=False)
|
|
1002
|
+
# A server that does not answer, such as an app stopped at a breakpoint,
|
|
1003
|
+
# would otherwise hold the request for the client's own timeout.
|
|
1004
|
+
client.timeout = max(deadline - time.monotonic(), READY_INTERVAL)
|
|
1005
|
+
meta = client.get(META)
|
|
1006
|
+
except (DiscoveryError, LustroError) as exc:
|
|
1007
|
+
last: Exception = exc
|
|
1008
|
+
# Every Lustro server routes _meta, so a 404 there is from another server,
|
|
1009
|
+
# such as the one of another app on the port that the app's prefs keep from
|
|
1010
|
+
# its last start. The app gets that port, or another one, when it starts.
|
|
1011
|
+
other_server = None
|
|
1012
|
+
if isinstance(exc, LustroError) and exc.status == 404:
|
|
1013
|
+
other_server = client.base_url
|
|
1014
|
+
if device_port is not None:
|
|
1015
|
+
other_server = "port {} of the device (through {})".format(device_port, client.base_url)
|
|
1016
|
+
# An error response other than a busy or failing server, such as a 401 for a
|
|
1017
|
+
# --token that is not the app's, does not change when ready tries again. A
|
|
1018
|
+
# discovered token does: the prefs keep the token of the app's last process
|
|
1019
|
+
# until the new process writes its own.
|
|
1020
|
+
if (
|
|
1021
|
+
other_server is None
|
|
1022
|
+
and isinstance(exc, LustroError)
|
|
1023
|
+
and exc.status is not None
|
|
1024
|
+
and exc.status < 500
|
|
1025
|
+
and exc.status != 429
|
|
1026
|
+
and not (exc.status == 401 and _token_was_discovered(args))
|
|
1027
|
+
):
|
|
1028
|
+
break
|
|
1029
|
+
if not checked_early:
|
|
1030
|
+
# Asked before the checks: a package manager that answers then also
|
|
1031
|
+
# answered the checks.
|
|
1032
|
+
answers = _package_manager_answers(args)
|
|
1033
|
+
cause = _cause_from_adb(args)
|
|
1034
|
+
if cause is not None and cause.exit_code in (exitcodes.NOT_INSTALLED, exitcodes.NO_RUNTIME):
|
|
1035
|
+
print("error: {}".format(cause), file=sys.stderr)
|
|
1036
|
+
return cause.exit_code
|
|
1037
|
+
# While an emulator starts, adb first finds no device, and then a package
|
|
1038
|
+
# manager that does not answer yet: the checks then run again on the next try.
|
|
1039
|
+
checked_early = answers if cause is None else cause.exit_code != exitcodes.NO_DEVICE
|
|
1040
|
+
else:
|
|
1041
|
+
_warn_if_newer_protocol(meta)
|
|
1042
|
+
if args.json:
|
|
1043
|
+
_emit(
|
|
1044
|
+
{
|
|
1045
|
+
"endpoint": client.base_url,
|
|
1046
|
+
"libraryVersion": meta.get("libraryVersion") if isinstance(meta, dict) else None,
|
|
1047
|
+
"protocolVersion": meta.get("protocolVersion") if isinstance(meta, dict) else None,
|
|
1048
|
+
},
|
|
1049
|
+
raw_json=True,
|
|
1050
|
+
)
|
|
1051
|
+
else:
|
|
1052
|
+
print(client.base_url)
|
|
1053
|
+
return exitcodes.OK
|
|
1054
|
+
remaining = deadline - time.monotonic()
|
|
1055
|
+
if remaining <= 0:
|
|
1056
|
+
break
|
|
1057
|
+
time.sleep(min(READY_INTERVAL, remaining))
|
|
1058
|
+
if other_server is not None:
|
|
1059
|
+
cause = _cause_from_adb(args)
|
|
1060
|
+
code = exitcodes.NOT_REACHABLE if cause is None else cause.exit_code
|
|
1061
|
+
other = "server answers on {}: it answered 404 to GET {}, a route that every Lustro server has.".format(
|
|
1062
|
+
other_server, META
|
|
1063
|
+
)
|
|
1064
|
+
message = "another " + other if cause is None else "{} Another {}".format(cause, other)
|
|
1065
|
+
print("error: the app's server did not answer within {} s: {}".format(_seconds(args.timeout), message), file=sys.stderr)
|
|
1066
|
+
return code
|
|
1067
|
+
if isinstance(last, DiscoveryError):
|
|
1068
|
+
last = diagnose(args.device, args.package) or last
|
|
1069
|
+
code, message = failure(args, last, ready_timeout=args.timeout)
|
|
1070
|
+
if isinstance(last, LustroError) and last.status is not None:
|
|
1071
|
+
# The server answered, with an error.
|
|
1072
|
+
print("error: {}".format(message), file=sys.stderr)
|
|
1073
|
+
else:
|
|
1074
|
+
print("error: the app's server did not answer within {} s: {}".format(_seconds(args.timeout), message), file=sys.stderr)
|
|
1075
|
+
return code
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
def cmd_schema(args: argparse.Namespace) -> int:
|
|
1079
|
+
client = _build_client(args)
|
|
1080
|
+
if args.tab_id:
|
|
1081
|
+
path = "/api/v1/{}/_schema".format(args.tab_id)
|
|
1082
|
+
else:
|
|
1083
|
+
path = "/api/v1/_schema"
|
|
1084
|
+
_emit(client.get(path), raw_json=args.json)
|
|
1085
|
+
return 0
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
# ── api: any route ─────────────────────────────────────────────────────────────
|
|
1089
|
+
|
|
1090
|
+
|
|
1091
|
+
# A URL starts with a scheme. A query in PATH can still hold one, such as ?search=https://x.
|
|
1092
|
+
_URL_START = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://")
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
def _api_path(path: str) -> str:
|
|
1096
|
+
"""The route to request: PATH as it is, or after /api/v1/ when it has no leading slash."""
|
|
1097
|
+
if _URL_START.match(path):
|
|
1098
|
+
raise UsageError("PATH is a route such as /api/v1/_meta or network/transactions, not a URL: {}".format(path))
|
|
1099
|
+
return path if path.startswith("/") else API_ROOT + path
|
|
1100
|
+
|
|
1101
|
+
|
|
1102
|
+
def _api_body(args: argparse.Namespace) -> Any:
|
|
1103
|
+
"""The JSON request body from --body or --input, or None for no body."""
|
|
1104
|
+
if args.body is not None:
|
|
1105
|
+
text, source = args.body, "--body"
|
|
1106
|
+
elif args.input is not None:
|
|
1107
|
+
source = "--input " + args.input
|
|
1108
|
+
try:
|
|
1109
|
+
if args.input == "-":
|
|
1110
|
+
text = sys.stdin.read()
|
|
1111
|
+
else:
|
|
1112
|
+
with open(args.input, "r", encoding="utf-8") as fh:
|
|
1113
|
+
text = fh.read()
|
|
1114
|
+
except (OSError, ValueError) as exc:
|
|
1115
|
+
# ValueError: a file that is not UTF-8, such as a UTF-16 file from PowerShell.
|
|
1116
|
+
raise UsageError("could not read {}: {}".format(args.input, exc))
|
|
1117
|
+
else:
|
|
1118
|
+
return None
|
|
1119
|
+
try:
|
|
1120
|
+
return json.loads(text)
|
|
1121
|
+
except ValueError as exc:
|
|
1122
|
+
raise UsageError("{} is not JSON: {}".format(source, exc))
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
def _is_json_type(content_type: Optional[str]) -> bool:
|
|
1126
|
+
media_type = (content_type or "").split(";", 1)[0].strip().lower()
|
|
1127
|
+
return media_type == "application/json" or media_type.endswith("+json")
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def cmd_api(args: argparse.Namespace) -> int:
|
|
1131
|
+
"""Send one request to any route and print the response body."""
|
|
1132
|
+
path = _api_path(args.path)
|
|
1133
|
+
body = _api_body(args)
|
|
1134
|
+
client = _build_client(args)
|
|
1135
|
+
if args.param or urllib.parse.urlsplit(path).query:
|
|
1136
|
+
note = unwarned_parameters_note(client, "`lustro schema <tabId>`")
|
|
1137
|
+
if note:
|
|
1138
|
+
print("note: {}".format(note), file=sys.stderr)
|
|
1139
|
+
response = client.request_raw(args.method, path, params=args.param, json_body=body)
|
|
1140
|
+
if not response.data:
|
|
1141
|
+
return 0
|
|
1142
|
+
if _is_json_type(response.content_type):
|
|
1143
|
+
try:
|
|
1144
|
+
decoded = json.loads(response.data.decode("utf-8"))
|
|
1145
|
+
except (ValueError, UnicodeDecodeError):
|
|
1146
|
+
pass
|
|
1147
|
+
else:
|
|
1148
|
+
print(_dumps(decoded, indent=sys.stdout.isatty()))
|
|
1149
|
+
return 0
|
|
1150
|
+
sys.stdout.buffer.write(response.data)
|
|
1151
|
+
sys.stdout.flush()
|
|
1152
|
+
return 0
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
# ── screen: the app's windows and UI tree ─────────────────────────────────────
|
|
1156
|
+
|
|
1157
|
+
SCREEN = "/api/v1/screen"
|
|
1158
|
+
# The longest settle that the tab takes, in milliseconds.
|
|
1159
|
+
MAX_SETTLE_MS = 10_000
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
def _settle_ms(value: str) -> int:
|
|
1163
|
+
try:
|
|
1164
|
+
ms = int(value)
|
|
1165
|
+
except ValueError:
|
|
1166
|
+
raise argparse.ArgumentTypeError("must be a whole number of milliseconds, such as 500")
|
|
1167
|
+
if not 0 <= ms <= MAX_SETTLE_MS:
|
|
1168
|
+
raise argparse.ArgumentTypeError("must be from 0 to {}".format(MAX_SETTLE_MS))
|
|
1169
|
+
return ms
|
|
1170
|
+
|
|
1171
|
+
|
|
1172
|
+
def _is_interesting(node: dict) -> bool:
|
|
1173
|
+
"""Whether a node says something about the screen: a text, a tag, a role, an
|
|
1174
|
+
action, or a state. The containers that only lay out others are left out."""
|
|
1175
|
+
keys = ("text", "editableText", "contentDescription", "testTag", "role", "actions", "toggle", "error", "stateDescription")
|
|
1176
|
+
return any(key in node for key in keys) or node.get("selected") is True
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
def _rect_text(rect: Optional[dict]) -> str:
|
|
1180
|
+
if not rect:
|
|
1181
|
+
return "(not on screen)"
|
|
1182
|
+
return "[{},{}][{},{}]".format(rect["left"], rect["top"], rect["right"], rect["bottom"])
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def _quoted(value: str, limit: int = 60) -> str:
|
|
1186
|
+
one_line = " ".join(value.split())
|
|
1187
|
+
if len(one_line) > limit:
|
|
1188
|
+
one_line = one_line[: limit - 1] + "…"
|
|
1189
|
+
return json.dumps(one_line, ensure_ascii=False)
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
def _node_line(node: dict) -> str:
|
|
1193
|
+
"""One node as a line: its id, what it is, its text, tag, states, actions, and
|
|
1194
|
+
where it is on the screen, in uiautomator's bounds format."""
|
|
1195
|
+
if node.get("role"):
|
|
1196
|
+
what = node["role"]
|
|
1197
|
+
elif node.get("className"):
|
|
1198
|
+
what = node["className"].rsplit(".", 1)[-1]
|
|
1199
|
+
else:
|
|
1200
|
+
what = "node"
|
|
1201
|
+
parts = [node["id"], what]
|
|
1202
|
+
if node.get("text"):
|
|
1203
|
+
parts.append(_quoted(" / ".join(node["text"])))
|
|
1204
|
+
if "editableText" in node:
|
|
1205
|
+
parts.append("value=" + _quoted(node["editableText"]))
|
|
1206
|
+
if node.get("contentDescription"):
|
|
1207
|
+
parts.append("desc=" + _quoted(" / ".join(node["contentDescription"])))
|
|
1208
|
+
if node.get("testTag"):
|
|
1209
|
+
parts.append("#" + node["testTag"])
|
|
1210
|
+
resource = node.get("resourceId")
|
|
1211
|
+
if resource and ":id/" in resource:
|
|
1212
|
+
parts.append("id=" + resource.split(":id/", 1)[1])
|
|
1213
|
+
flags = []
|
|
1214
|
+
if node.get("enabled") is False:
|
|
1215
|
+
flags.append("disabled")
|
|
1216
|
+
for key in ("focused", "password", "clipped"):
|
|
1217
|
+
if node.get(key):
|
|
1218
|
+
flags.append(key)
|
|
1219
|
+
if node.get("selected") is True:
|
|
1220
|
+
flags.append("selected")
|
|
1221
|
+
if node.get("toggle"):
|
|
1222
|
+
flags.append(node["toggle"])
|
|
1223
|
+
if node.get("error"):
|
|
1224
|
+
flags.append("error=" + _quoted(node["error"]))
|
|
1225
|
+
for axis, key in (("v", "verticalScroll"), ("h", "horizontalScroll")):
|
|
1226
|
+
scroll = node.get(key)
|
|
1227
|
+
if scroll:
|
|
1228
|
+
value = "{:g}".format(scroll["value"])
|
|
1229
|
+
flags.append("scroll-{} {}/{}".format(axis, value, "{:g}".format(scroll["max"]) if scroll.get("max") is not None else "?"))
|
|
1230
|
+
actions = node.get("actions") or []
|
|
1231
|
+
names = {"OnClick": "click", "OnLongClick": "long-click", "SetText": "set-text", "ScrollBy": "scroll", "ScrollToIndex": "scroll-to-index"}
|
|
1232
|
+
flags.extend(names[a] for a in actions if a in names)
|
|
1233
|
+
parts.extend(flags)
|
|
1234
|
+
parts.append(_rect_text(node.get("visibleBounds")))
|
|
1235
|
+
return " ".join(parts)
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def _print_tree(tree: dict, show_all: bool) -> None:
|
|
1239
|
+
for index, window in enumerate(tree.get("windows") or []):
|
|
1240
|
+
header = ["window {}".format(index), window.get("kind") or "other"]
|
|
1241
|
+
if window.get("title"):
|
|
1242
|
+
header.append(window["title"])
|
|
1243
|
+
header.append("focus" if window.get("hasWindowFocus") else "no-focus")
|
|
1244
|
+
if not window.get("visible"):
|
|
1245
|
+
header.append("hidden")
|
|
1246
|
+
header.append(_rect_text(window.get("bounds")))
|
|
1247
|
+
print(" ".join(header))
|
|
1248
|
+
nodes = window.get("nodes") or []
|
|
1249
|
+
by_id = {node["id"]: node for node in nodes}
|
|
1250
|
+
shown = {
|
|
1251
|
+
node["id"]
|
|
1252
|
+
for node in nodes
|
|
1253
|
+
if show_all or (node.get("visibleBounds") is not None and _is_interesting(node))
|
|
1254
|
+
}
|
|
1255
|
+
for node in nodes:
|
|
1256
|
+
if node["id"] not in shown:
|
|
1257
|
+
continue
|
|
1258
|
+
depth = 0
|
|
1259
|
+
parent = node.get("parent")
|
|
1260
|
+
while parent is not None and parent in by_id:
|
|
1261
|
+
if parent in shown:
|
|
1262
|
+
depth += 1
|
|
1263
|
+
parent = by_id[parent].get("parent")
|
|
1264
|
+
print(" " * (depth + 1) + _node_line(node))
|
|
1265
|
+
settle = tree.get("settle")
|
|
1266
|
+
if settle:
|
|
1267
|
+
if settle.get("settled"):
|
|
1268
|
+
print("settled after {} frame(s), {} ms".format(settle.get("frames"), settle.get("waitedMs")))
|
|
1269
|
+
else:
|
|
1270
|
+
print("not settled after {} ms: the tree is the last read".format(settle.get("waitedMs")))
|
|
1271
|
+
if not tree.get("windows"):
|
|
1272
|
+
print("no window: the app shows none, or its activity is not started")
|
|
1273
|
+
elif not any(w.get("hasWindowFocus") for w in tree["windows"]):
|
|
1274
|
+
print("no window of the app has the focus: another app's window, such as a permission dialog, may be on top")
|
|
1275
|
+
if tree.get("context") is not None:
|
|
1276
|
+
print("context: " + _dumps(tree["context"], indent=False))
|
|
1277
|
+
for key in ("contextError", "composeError"):
|
|
1278
|
+
if tree.get(key):
|
|
1279
|
+
print("{}: {}".format(key, tree[key]))
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def cmd_screen_tree(args: argparse.Namespace) -> int:
|
|
1283
|
+
params = {"merged": "false" if args.unmerged else None, "settle": str(args.settle) if args.settle else None}
|
|
1284
|
+
tree = _build_client(args).get(SCREEN + "/tree", params=params)
|
|
1285
|
+
if args.json:
|
|
1286
|
+
_emit(tree, raw_json=True)
|
|
1287
|
+
else:
|
|
1288
|
+
_print_tree(tree, args.all)
|
|
1289
|
+
return 0
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
# ── net subcommands ────────────────────────────────────────────────────────────
|
|
1293
|
+
|
|
1294
|
+
|
|
1295
|
+
def _require_regex(client: LustroClient, args: argparse.Namespace, command: str) -> None:
|
|
1296
|
+
if args.regex:
|
|
1297
|
+
require_protocol(client, command, "--regex")
|
|
1298
|
+
|
|
1299
|
+
|
|
1300
|
+
def cmd_net_list(args: argparse.Namespace) -> int:
|
|
1301
|
+
client = _build_client(args)
|
|
1302
|
+
_require_regex(client, args, "net list")
|
|
1303
|
+
data = client.get(TRANSACTIONS, params=_search_params(args))
|
|
1304
|
+
_note_if_paused(data)
|
|
1305
|
+
items = _list_items(data)
|
|
1306
|
+
_check_fields(args, items)
|
|
1307
|
+
# The server lists the newest transaction first.
|
|
1308
|
+
matched = [tx for tx in items if _matches(tx, args)]
|
|
1309
|
+
shown = matched if args.all else matched[: args.last]
|
|
1310
|
+
id_length = _short_id_length(items)
|
|
1311
|
+
for tx in shown:
|
|
1312
|
+
_print_transaction(tx, args, id_length)
|
|
1313
|
+
if len(shown) < len(matched):
|
|
1314
|
+
# stderr, so that the JSON Lines on stdout stay one object per line. The
|
|
1315
|
+
# flush puts it after the rows when a reader merges the two streams.
|
|
1316
|
+
sys.stdout.flush()
|
|
1317
|
+
print(
|
|
1318
|
+
"showing the newest {} of {}, use --all for every row".format(len(shown), len(matched)),
|
|
1319
|
+
file=sys.stderr,
|
|
1320
|
+
)
|
|
1321
|
+
return 0
|
|
1322
|
+
|
|
1323
|
+
|
|
1324
|
+
def cmd_net_state(args: argparse.Namespace) -> int:
|
|
1325
|
+
"""Print the capture state. The wire sends it only with the transaction list."""
|
|
1326
|
+
client = _build_client(args)
|
|
1327
|
+
data = client.get(TRANSACTIONS)
|
|
1328
|
+
state = data.get("state") if isinstance(data, dict) else None
|
|
1329
|
+
if not isinstance(state, dict):
|
|
1330
|
+
state = {}
|
|
1331
|
+
if args.json:
|
|
1332
|
+
_emit(state, raw_json=True)
|
|
1333
|
+
return 0
|
|
1334
|
+
print(
|
|
1335
|
+
"paused={} overwriteMode={} throttleDelayMs={}".format(
|
|
1336
|
+
*(json.dumps(state.get(key)) for key in ("paused", "overwriteMode", "throttleDelayMs"))
|
|
1337
|
+
)
|
|
1338
|
+
)
|
|
1339
|
+
capture_filter = state.get("captureFilter")
|
|
1340
|
+
if isinstance(capture_filter, dict):
|
|
1341
|
+
print(
|
|
1342
|
+
"capture filter: skipped={} failed={} ({})".format(
|
|
1343
|
+
capture_filter.get("skipped"), capture_filter.get("failed"), capture_filter.get("description")
|
|
1344
|
+
)
|
|
1345
|
+
)
|
|
1346
|
+
else:
|
|
1347
|
+
print("capture filter: none")
|
|
1348
|
+
# From protocol 1.9.
|
|
1349
|
+
mock_rules = state.get("mockRules")
|
|
1350
|
+
if isinstance(mock_rules, dict):
|
|
1351
|
+
print("mock rules: enabled={}".format(mock_rules.get("enabled")))
|
|
1352
|
+
return 0
|
|
1353
|
+
|
|
1354
|
+
|
|
1355
|
+
def _print_changes(items: List[Any], printed: Dict[Any, bool], args: argparse.Namespace) -> Dict[Any, bool]:
|
|
1356
|
+
"""Print, oldest first, the matching transactions that aren't printed yet, and
|
|
1357
|
+
again those that were in flight when printed and are complete now.
|
|
1358
|
+
|
|
1359
|
+
``printed`` maps each printed id to whether it was complete. Returns it for
|
|
1360
|
+
the transactions still listed.
|
|
1361
|
+
"""
|
|
1362
|
+
listed: Dict[Any, bool] = {}
|
|
1363
|
+
id_length = _short_id_length(items)
|
|
1364
|
+
for tx in reversed(items):
|
|
1365
|
+
if not isinstance(tx, dict) or not _matches(tx, args):
|
|
1366
|
+
continue
|
|
1367
|
+
tx_id = tx.get("id")
|
|
1368
|
+
complete = _is_complete(tx)
|
|
1369
|
+
if tx_id not in printed:
|
|
1370
|
+
_print_transaction(tx, args, id_length)
|
|
1371
|
+
elif complete and not printed[tx_id]:
|
|
1372
|
+
_print_transaction(tx, args, id_length, update=True)
|
|
1373
|
+
listed[tx_id] = complete
|
|
1374
|
+
return listed
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
def cmd_net_poll(args: argparse.Namespace) -> int:
|
|
1378
|
+
client = _build_client(args)
|
|
1379
|
+
_require_regex(client, args, "net poll")
|
|
1380
|
+
poller = CursorState()
|
|
1381
|
+
printed: Dict[Any, bool] = {}
|
|
1382
|
+
first = True
|
|
1383
|
+
try:
|
|
1384
|
+
while True:
|
|
1385
|
+
params = dict(_search_params(args), cursor=poller.cursor)
|
|
1386
|
+
try:
|
|
1387
|
+
data = client.get(TRANSACTIONS, params=params)
|
|
1388
|
+
except LustroError as exc:
|
|
1389
|
+
if _is_search_error(exc):
|
|
1390
|
+
raise
|
|
1391
|
+
print("poll error: {}".format(exc), file=sys.stderr)
|
|
1392
|
+
if args.once:
|
|
1393
|
+
return 1
|
|
1394
|
+
time.sleep(args.interval)
|
|
1395
|
+
continue
|
|
1396
|
+
poller.apply(data)
|
|
1397
|
+
if first:
|
|
1398
|
+
_note_if_paused(data)
|
|
1399
|
+
_check_fields(args, poller.items)
|
|
1400
|
+
first = False
|
|
1401
|
+
printed = _print_changes(poller.items, printed, args)
|
|
1402
|
+
# A reader at the other end of a pipe gets each batch as it comes.
|
|
1403
|
+
sys.stdout.flush()
|
|
1404
|
+
if args.once:
|
|
1405
|
+
break
|
|
1406
|
+
time.sleep(args.interval)
|
|
1407
|
+
except KeyboardInterrupt: # pragma: no cover - interactive
|
|
1408
|
+
return 0
|
|
1409
|
+
return 0
|
|
1410
|
+
|
|
1411
|
+
|
|
1412
|
+
def _run_action(command: List[str], timeout: float) -> Optional[str]:
|
|
1413
|
+
"""Run the command that makes the app send the awaited request. Returns what
|
|
1414
|
+
went wrong, or None. Its output shows only when it fails, so that stdout
|
|
1415
|
+
keeps only the match."""
|
|
1416
|
+
try:
|
|
1417
|
+
proc = subprocess.run(
|
|
1418
|
+
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, timeout=timeout
|
|
1419
|
+
)
|
|
1420
|
+
except subprocess.TimeoutExpired:
|
|
1421
|
+
return "{} did not finish within {} s".format(command[0], _seconds(timeout))
|
|
1422
|
+
except OSError as exc:
|
|
1423
|
+
return "could not run {}: {}".format(command[0], exc)
|
|
1424
|
+
if proc.returncode != 0:
|
|
1425
|
+
output = proc.stdout.decode("utf-8", "replace").strip()
|
|
1426
|
+
if output:
|
|
1427
|
+
print(output, file=sys.stderr)
|
|
1428
|
+
return "{} exited with status {}".format(command[0], proc.returncode)
|
|
1429
|
+
return None
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
def _first_new_match(items: List[Any], finished_before: Set[Any], args: argparse.Namespace) -> Optional[dict]:
|
|
1433
|
+
"""The matching request that finished first, of those not finished at the first poll."""
|
|
1434
|
+
candidates = [
|
|
1435
|
+
tx
|
|
1436
|
+
for tx in reversed(items)
|
|
1437
|
+
if isinstance(tx, dict)
|
|
1438
|
+
and tx.get("id") not in finished_before
|
|
1439
|
+
and _is_complete(tx)
|
|
1440
|
+
and _matches(tx, args)
|
|
1441
|
+
]
|
|
1442
|
+
if not candidates:
|
|
1443
|
+
return None
|
|
1444
|
+
return min(candidates, key=lambda tx: tx.get("completedAt") or 0)
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
def cmd_net_wait(args: argparse.Namespace) -> int:
|
|
1448
|
+
"""Wait until a matching request finishes, print it, and exit 0; exit 1 at the timeout."""
|
|
1449
|
+
client = _build_client(args)
|
|
1450
|
+
_require_regex(client, args, "net wait")
|
|
1451
|
+
deadline = time.monotonic() + args.timeout
|
|
1452
|
+
|
|
1453
|
+
def time_left() -> float:
|
|
1454
|
+
# At least one interval, so that the last poll can still get an answer.
|
|
1455
|
+
return max(deadline - time.monotonic(), args.interval)
|
|
1456
|
+
|
|
1457
|
+
def poll(cursor: Optional[str]) -> Any:
|
|
1458
|
+
# An app that doesn't answer, such as one stopped at a breakpoint, would
|
|
1459
|
+
# otherwise hold each request for the client's own timeout.
|
|
1460
|
+
client.timeout = time_left()
|
|
1461
|
+
return client.get(TRANSACTIONS, params=dict(_search_params(args), cursor=cursor))
|
|
1462
|
+
|
|
1463
|
+
poller = CursorState()
|
|
1464
|
+
data = poll(None)
|
|
1465
|
+
_note_if_paused(data)
|
|
1466
|
+
poller.apply(data)
|
|
1467
|
+
_check_fields(args, poller.items)
|
|
1468
|
+
finished_before = {tx.get("id") for tx in _list_items(data) if _is_complete(tx)}
|
|
1469
|
+
if args.action:
|
|
1470
|
+
error = _run_action(args.action, time_left())
|
|
1471
|
+
if error:
|
|
1472
|
+
print("error: {}".format(error), file=sys.stderr)
|
|
1473
|
+
return 2
|
|
1474
|
+
last_error = None
|
|
1475
|
+
while True:
|
|
1476
|
+
match = _first_new_match(poller.items, finished_before, args)
|
|
1477
|
+
if match is not None:
|
|
1478
|
+
_print_transaction(match, args, _short_id_length(poller.items))
|
|
1479
|
+
return 0
|
|
1480
|
+
remaining = deadline - time.monotonic()
|
|
1481
|
+
if remaining <= 0:
|
|
1482
|
+
break
|
|
1483
|
+
time.sleep(min(args.interval, remaining))
|
|
1484
|
+
try:
|
|
1485
|
+
poller.apply(poll(poller.cursor))
|
|
1486
|
+
except LustroError as exc:
|
|
1487
|
+
if _is_search_error(exc):
|
|
1488
|
+
raise
|
|
1489
|
+
# The action can put the app in the background for a moment, so keep polling.
|
|
1490
|
+
if str(exc) != last_error:
|
|
1491
|
+
print("poll error: {}".format(exc), file=sys.stderr)
|
|
1492
|
+
last_error = str(exc)
|
|
1493
|
+
print("error: no matching request finished within {} s".format(_seconds(args.timeout)), file=sys.stderr)
|
|
1494
|
+
earlier = [
|
|
1495
|
+
tx for tx in poller.items if isinstance(tx, dict) and tx.get("id") in finished_before and _matches(tx, args)
|
|
1496
|
+
]
|
|
1497
|
+
if earlier and not args.action:
|
|
1498
|
+
print(
|
|
1499
|
+
" hint: wait ignores requests that finished before it started, and {} of them match "
|
|
1500
|
+
"(newest: {}). To catch a fast request, give the action after --, so that wait "
|
|
1501
|
+
"starts first.".format(len(earlier), earlier[0].get("id")),
|
|
1502
|
+
file=sys.stderr,
|
|
1503
|
+
)
|
|
1504
|
+
return 1
|
|
1505
|
+
|
|
1506
|
+
|
|
1507
|
+
def cmd_net_get(args: argparse.Namespace) -> int:
|
|
1508
|
+
client = _build_client(args)
|
|
1509
|
+
tx = client.get(TRANSACTIONS + "/" + _resolve_id(client, args.id))
|
|
1510
|
+
if isinstance(tx, dict):
|
|
1511
|
+
if args.no_body:
|
|
1512
|
+
tx.pop("requestBody", None)
|
|
1513
|
+
tx.pop("responseBody", None)
|
|
1514
|
+
elif not args.full:
|
|
1515
|
+
_cut_bodies(tx, args.max_body)
|
|
1516
|
+
_emit(tx, raw_json=args.json)
|
|
1517
|
+
return 0
|
|
1518
|
+
|
|
1519
|
+
|
|
1520
|
+
def cmd_net_body(args: argparse.Namespace) -> int:
|
|
1521
|
+
"""Save one captured body to a file, or write it to stdout."""
|
|
1522
|
+
client = _build_client(args)
|
|
1523
|
+
tx_path = TRANSACTIONS + "/" + _resolve_id(client, args.id)
|
|
1524
|
+
# The detail says whether the body is binary and whether capture cut it off.
|
|
1525
|
+
tx = client.get(tx_path)
|
|
1526
|
+
direction = args.direction
|
|
1527
|
+
binary = bool(tx.get(direction + "BodyBinary"))
|
|
1528
|
+
if args.output is None and binary and sys.stdout.isatty():
|
|
1529
|
+
print(
|
|
1530
|
+
"error: the {} body is binary ({}); save it with -o FILE or redirect stdout".format(
|
|
1531
|
+
direction, tx.get(direction + "ContentType") or "unknown type"
|
|
1532
|
+
),
|
|
1533
|
+
file=sys.stderr,
|
|
1534
|
+
)
|
|
1535
|
+
return 2
|
|
1536
|
+
body = client.get_raw(tx_path + "/body/" + direction)
|
|
1537
|
+
if args.output is None:
|
|
1538
|
+
sys.stdout.buffer.write(body.data)
|
|
1539
|
+
sys.stdout.flush()
|
|
1540
|
+
else:
|
|
1541
|
+
try:
|
|
1542
|
+
with open(args.output, "wb") as fh:
|
|
1543
|
+
fh.write(body.data)
|
|
1544
|
+
except OSError as exc:
|
|
1545
|
+
print("could not write body file {}: {}".format(args.output, exc), file=sys.stderr)
|
|
1546
|
+
return 2
|
|
1547
|
+
truncated = bool(tx.get(direction + "BodyTruncated"))
|
|
1548
|
+
if truncated:
|
|
1549
|
+
full = tx.get(direction + "BodyBytes")
|
|
1550
|
+
print(
|
|
1551
|
+
"warning: capture kept only the first {} bytes of the {} body{}".format(
|
|
1552
|
+
len(body.data), direction, "" if full is None else " ({} bytes in full)".format(full)
|
|
1553
|
+
),
|
|
1554
|
+
file=sys.stderr,
|
|
1555
|
+
)
|
|
1556
|
+
if args.output is not None:
|
|
1557
|
+
summary = {
|
|
1558
|
+
"path": args.output,
|
|
1559
|
+
"bytes": len(body.data),
|
|
1560
|
+
"contentType": body.content_type,
|
|
1561
|
+
"binary": binary,
|
|
1562
|
+
"truncated": truncated,
|
|
1563
|
+
}
|
|
1564
|
+
if args.json:
|
|
1565
|
+
_emit(summary, raw_json=True)
|
|
1566
|
+
else:
|
|
1567
|
+
print("saved {} bytes ({}) to {}".format(len(body.data), body.content_type or "no type", args.output))
|
|
1568
|
+
return 0
|
|
1569
|
+
|
|
1570
|
+
|
|
1571
|
+
def _export_entries(har: Any) -> List[Any]:
|
|
1572
|
+
entries = har.get("log", {}).get("entries") if isinstance(har, dict) else None
|
|
1573
|
+
if not isinstance(entries, list):
|
|
1574
|
+
raise LustroError("invalid_response", "the export is not a HAR document: it has no log.entries")
|
|
1575
|
+
return entries
|
|
1576
|
+
|
|
1577
|
+
|
|
1578
|
+
def _export_har(client: LustroClient, ids: Optional[List[str]]) -> Any:
|
|
1579
|
+
"""The HAR document of the transactions that ``ids`` names, or of every one.
|
|
1580
|
+
Many ids go in batches, and the entries of each batch join the first one's."""
|
|
1581
|
+
if ids is None:
|
|
1582
|
+
har = client.get(EXPORT, params={"format": "har"})
|
|
1583
|
+
_export_entries(har)
|
|
1584
|
+
return har
|
|
1585
|
+
har = None
|
|
1586
|
+
for start in range(0, len(ids), EXPORT_BATCH):
|
|
1587
|
+
batch = client.get(EXPORT, params={"format": "har", "ids": ",".join(ids[start : start + EXPORT_BATCH])})
|
|
1588
|
+
entries = _export_entries(batch)
|
|
1589
|
+
if har is None:
|
|
1590
|
+
har = batch
|
|
1591
|
+
else:
|
|
1592
|
+
_export_entries(har).extend(entries)
|
|
1593
|
+
# Each batch is oldest first, and the times are ISO 8601 in UTC, so they sort as text.
|
|
1594
|
+
_export_entries(har).sort(key=lambda entry: str(entry.get("startedDateTime", "")))
|
|
1595
|
+
return har
|
|
1596
|
+
|
|
1597
|
+
|
|
1598
|
+
def cmd_net_export(args: argparse.Namespace) -> int:
|
|
1599
|
+
"""Save captured transactions as a HAR file, or write it to stdout."""
|
|
1600
|
+
client = _build_client(args)
|
|
1601
|
+
ids = None
|
|
1602
|
+
if args.ids is not None:
|
|
1603
|
+
# In the order given, each id once.
|
|
1604
|
+
ids = list(dict.fromkeys(_resolve_ids(client, [given for group in args.ids for given in group])))
|
|
1605
|
+
har = _export_har(client, ids)
|
|
1606
|
+
entries = _export_entries(har)
|
|
1607
|
+
# Indented, as browser devtools write a HAR file, and as the console saves one.
|
|
1608
|
+
data = (json.dumps(har, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
|
|
1609
|
+
if args.har == "-":
|
|
1610
|
+
sys.stdout.buffer.write(data)
|
|
1611
|
+
sys.stdout.flush()
|
|
1612
|
+
else:
|
|
1613
|
+
try:
|
|
1614
|
+
with open(args.har, "wb") as fh:
|
|
1615
|
+
fh.write(data)
|
|
1616
|
+
except OSError as exc:
|
|
1617
|
+
print("could not write HAR file {}: {}".format(args.har, exc), file=sys.stderr)
|
|
1618
|
+
return 2
|
|
1619
|
+
exported = {entry.get("_lustro", {}).get("id") for entry in entries if isinstance(entry, dict)}
|
|
1620
|
+
missing = [tx_id for tx_id in ids or [] if tx_id not in exported]
|
|
1621
|
+
if missing:
|
|
1622
|
+
print(
|
|
1623
|
+
"warning: the app no longer has {} of the transactions, so the file leaves them out: {}".format(
|
|
1624
|
+
len(missing), ", ".join(missing)
|
|
1625
|
+
),
|
|
1626
|
+
file=sys.stderr,
|
|
1627
|
+
)
|
|
1628
|
+
if args.har != "-":
|
|
1629
|
+
if args.json:
|
|
1630
|
+
_emit({"path": args.har, "entries": len(entries), "bytes": len(data), "missing": missing}, raw_json=True)
|
|
1631
|
+
else:
|
|
1632
|
+
print("saved {} transactions ({} bytes) to {}".format(len(entries), len(data), args.har))
|
|
1633
|
+
return 0
|
|
1634
|
+
|
|
1635
|
+
|
|
1636
|
+
# ── net ws subcommands ─────────────────────────────────────────────────────────
|
|
1637
|
+
|
|
1638
|
+
|
|
1639
|
+
def cmd_net_ws_list(args: argparse.Namespace) -> int:
|
|
1640
|
+
client = _build_client(args)
|
|
1641
|
+
data = client.get(WEBSOCKETS)
|
|
1642
|
+
_note_if_paused(data, "no new socket is listed and no message is recorded")
|
|
1643
|
+
items = _list_items(data)
|
|
1644
|
+
_check_fields(args, items, component="WebSocketConnection", noun="connections")
|
|
1645
|
+
id_length = _short_id_length(items)
|
|
1646
|
+
# The server lists the newest connection first.
|
|
1647
|
+
for connection in items:
|
|
1648
|
+
if _prints_json_lines(args):
|
|
1649
|
+
if args.fields is not None:
|
|
1650
|
+
connection = {name: connection.get(name) for name in args.fields}
|
|
1651
|
+
print(_dumps(connection, indent=False))
|
|
1652
|
+
else:
|
|
1653
|
+
print(_format_ws_row(connection, id_length))
|
|
1654
|
+
return 0
|
|
1655
|
+
|
|
1656
|
+
|
|
1657
|
+
def cmd_net_ws_get(args: argparse.Namespace) -> int:
|
|
1658
|
+
client = _build_client(args)
|
|
1659
|
+
_emit(client.get(WEBSOCKETS + "/" + _resolve_ws_id(client, args.id)), raw_json=args.json)
|
|
1660
|
+
return 0
|
|
1661
|
+
|
|
1662
|
+
|
|
1663
|
+
def _print_events(items: List[dict], connection_id: str, args: argparse.Namespace) -> None:
|
|
1664
|
+
for event in items:
|
|
1665
|
+
if _prints_json_lines(args):
|
|
1666
|
+
if args.fields is not None:
|
|
1667
|
+
event = {name: event.get(name) for name in args.fields}
|
|
1668
|
+
print(_dumps(event, indent=False))
|
|
1669
|
+
else:
|
|
1670
|
+
print(_format_event_row(event, connection_id))
|
|
1671
|
+
|
|
1672
|
+
|
|
1673
|
+
def cmd_net_ws_events(args: argparse.Namespace) -> int:
|
|
1674
|
+
"""Print a connection's log, oldest first, and with --follow each new event as it comes."""
|
|
1675
|
+
client = _build_client(args)
|
|
1676
|
+
_require_regex(client, args, "net ws events")
|
|
1677
|
+
connection_id = _resolve_ws_id(client, args.id)
|
|
1678
|
+
path = WEBSOCKETS + "/" + connection_id + "/events"
|
|
1679
|
+
filters = {
|
|
1680
|
+
"direction": "sent" if args.sent else "received" if args.received else None,
|
|
1681
|
+
**_search_params(args),
|
|
1682
|
+
}
|
|
1683
|
+
data = client.get(path, params=dict(filters, limit=ALL_EVENTS if args.all else args.last))
|
|
1684
|
+
items = _list_items(data)
|
|
1685
|
+
_check_fields(args, items, component="WebSocketEvent", noun="events")
|
|
1686
|
+
_print_events(items, connection_id, args)
|
|
1687
|
+
if not args.follow:
|
|
1688
|
+
return 0
|
|
1689
|
+
cursor = data.get("cursor") if isinstance(data, dict) else None
|
|
1690
|
+
try:
|
|
1691
|
+
while True:
|
|
1692
|
+
# A reader at the other end of a pipe gets each batch as it comes.
|
|
1693
|
+
sys.stdout.flush()
|
|
1694
|
+
time.sleep(args.interval)
|
|
1695
|
+
try:
|
|
1696
|
+
data = client.get(path, params=dict(filters, cursor=cursor, limit=ALL_EVENTS))
|
|
1697
|
+
except LustroError as exc:
|
|
1698
|
+
if exc.error == "not_found" or _is_search_error(exc):
|
|
1699
|
+
# The app cleared or evicted the connection, or rejected the search.
|
|
1700
|
+
raise
|
|
1701
|
+
print("poll error: {}".format(exc), file=sys.stderr)
|
|
1702
|
+
continue
|
|
1703
|
+
if not isinstance(data, dict):
|
|
1704
|
+
continue
|
|
1705
|
+
status = data.get("status")
|
|
1706
|
+
if status != "unchanged":
|
|
1707
|
+
if status != "delta":
|
|
1708
|
+
print("note: the log started again, so these are its last events", file=sys.stderr)
|
|
1709
|
+
elif data.get("dropped"):
|
|
1710
|
+
print(
|
|
1711
|
+
"note: the log evicted {} events before this command got them".format(data["dropped"]),
|
|
1712
|
+
file=sys.stderr,
|
|
1713
|
+
)
|
|
1714
|
+
_print_events(_list_items(data), connection_id, args)
|
|
1715
|
+
cursor = data.get("cursor", cursor)
|
|
1716
|
+
except KeyboardInterrupt: # pragma: no cover - interactive
|
|
1717
|
+
return 0
|
|
1718
|
+
|
|
1719
|
+
|
|
1720
|
+
def cmd_net_ws_payload(args: argparse.Namespace) -> int:
|
|
1721
|
+
"""Save one message's payload to a file, or write it to stdout."""
|
|
1722
|
+
client = _build_client(args)
|
|
1723
|
+
connection_id = _resolve_ws_id(client, args.id)
|
|
1724
|
+
payload = client.get_raw("{}/{}/events/{}/payload".format(WEBSOCKETS, connection_id, args.seq))
|
|
1725
|
+
binary = not str(payload.content_type or "").startswith("text/")
|
|
1726
|
+
if args.output is None and binary and sys.stdout.isatty():
|
|
1727
|
+
print("error: the payload is binary; save it with -o FILE or redirect stdout", file=sys.stderr)
|
|
1728
|
+
return 2
|
|
1729
|
+
if args.output is None:
|
|
1730
|
+
sys.stdout.buffer.write(payload.data)
|
|
1731
|
+
sys.stdout.flush()
|
|
1732
|
+
return 0
|
|
1733
|
+
try:
|
|
1734
|
+
with open(args.output, "wb") as fh:
|
|
1735
|
+
fh.write(payload.data)
|
|
1736
|
+
except OSError as exc:
|
|
1737
|
+
print("could not write payload file {}: {}".format(args.output, exc), file=sys.stderr)
|
|
1738
|
+
return 2
|
|
1739
|
+
if args.json:
|
|
1740
|
+
_emit({"path": args.output, "bytes": len(payload.data), "binary": binary}, raw_json=True)
|
|
1741
|
+
else:
|
|
1742
|
+
print("saved {} bytes ({}) to {}".format(len(payload.data), "binary" if binary else "text", args.output))
|
|
1743
|
+
return 0
|
|
1744
|
+
|
|
1745
|
+
|
|
1746
|
+
def cmd_net_clear(args: argparse.Namespace) -> int:
|
|
1747
|
+
client = _build_client(args)
|
|
1748
|
+
_emit(client.post(NETWORK + "/clear"), raw_json=args.json)
|
|
1749
|
+
return 0
|
|
1750
|
+
|
|
1751
|
+
|
|
1752
|
+
def cmd_net_pause(args: argparse.Namespace) -> int:
|
|
1753
|
+
client = _build_client(args)
|
|
1754
|
+
_emit(client.post(NETWORK + "/pause"), raw_json=args.json)
|
|
1755
|
+
return 0
|
|
1756
|
+
|
|
1757
|
+
|
|
1758
|
+
def cmd_net_overwrite(args: argparse.Namespace) -> int:
|
|
1759
|
+
client = _build_client(args)
|
|
1760
|
+
_emit(client.post(NETWORK + "/overwrite-mode"), raw_json=args.json)
|
|
1761
|
+
return 0
|
|
1762
|
+
|
|
1763
|
+
|
|
1764
|
+
def cmd_net_throttle(args: argparse.Namespace) -> int:
|
|
1765
|
+
client = _build_client(args)
|
|
1766
|
+
_emit(client.post(NETWORK + "/throttle", json_body={"delayMs": args.ms}), raw_json=args.json)
|
|
1767
|
+
return 0
|
|
1768
|
+
|
|
1769
|
+
|
|
1770
|
+
# ── mock subcommands ───────────────────────────────────────────────────────────
|
|
1771
|
+
|
|
1772
|
+
# The failure names of a mock rule that protocol 1.12 defines.
|
|
1773
|
+
MOCK_FAILURES = ("timeout", "unknownHost", "connectionRefused", "connectionReset", "tls")
|
|
1774
|
+
|
|
1775
|
+
|
|
1776
|
+
def cmd_mock_list(args: argparse.Namespace) -> int:
|
|
1777
|
+
client = _build_client(args)
|
|
1778
|
+
data = client.get(NETWORK + "/rules")
|
|
1779
|
+
if args.json:
|
|
1780
|
+
_emit(data, raw_json=True)
|
|
1781
|
+
return 0
|
|
1782
|
+
for rule in (data.get("items") or []):
|
|
1783
|
+
enabled = "on " if rule.get("enabled") else "off"
|
|
1784
|
+
failure = rule.get("failure")
|
|
1785
|
+
print(
|
|
1786
|
+
"{id} [{enabled}] {method} {pattern} -> {outcome} hits={hits}".format(
|
|
1787
|
+
id=rule.get("id"),
|
|
1788
|
+
enabled=enabled,
|
|
1789
|
+
method=rule.get("method") or "*",
|
|
1790
|
+
pattern=rule.get("urlPattern"),
|
|
1791
|
+
outcome="failure={}".format(failure) if failure else rule.get("statusCode"),
|
|
1792
|
+
hits=rule.get("hitCount", 0),
|
|
1793
|
+
)
|
|
1794
|
+
)
|
|
1795
|
+
return 0
|
|
1796
|
+
|
|
1797
|
+
|
|
1798
|
+
def cmd_mock_add(args: argparse.Namespace) -> int:
|
|
1799
|
+
# The app ignores the response of a failure rule, so a response given with
|
|
1800
|
+
# one is a mistake, not something to drop without a word.
|
|
1801
|
+
if args.failure is not None and (args.status is not None or args.body is not None or args.header):
|
|
1802
|
+
print("--failure fails the request, so it takes no --status, --body, or --header", file=sys.stderr)
|
|
1803
|
+
return 2
|
|
1804
|
+
client = _build_client(args)
|
|
1805
|
+
if args.failure is not None:
|
|
1806
|
+
require_protocol(client, "mock add", "--failure")
|
|
1807
|
+
rule: dict = {"urlPattern": args.url_pattern}
|
|
1808
|
+
if args.id is not None:
|
|
1809
|
+
rule["id"] = args.id
|
|
1810
|
+
if args.name is not None:
|
|
1811
|
+
rule["name"] = args.name
|
|
1812
|
+
if args.method is not None:
|
|
1813
|
+
rule["method"] = args.method
|
|
1814
|
+
if args.status is not None:
|
|
1815
|
+
rule["statusCode"] = args.status
|
|
1816
|
+
if args.body is not None:
|
|
1817
|
+
rule["responseBody"] = args.body
|
|
1818
|
+
if args.header:
|
|
1819
|
+
rule["responseHeaders"] = _parse_headers(args.header)
|
|
1820
|
+
if args.failure is not None:
|
|
1821
|
+
rule["failure"] = args.failure
|
|
1822
|
+
_emit(client.post(NETWORK + "/rules", json_body=rule), raw_json=args.json)
|
|
1823
|
+
return 0
|
|
1824
|
+
|
|
1825
|
+
|
|
1826
|
+
def cmd_mock_delete(args: argparse.Namespace) -> int:
|
|
1827
|
+
client = _build_client(args)
|
|
1828
|
+
_emit(client.post(NETWORK + "/rules/delete", json_body={"id": args.id}), raw_json=args.json)
|
|
1829
|
+
return 0
|
|
1830
|
+
|
|
1831
|
+
|
|
1832
|
+
def cmd_mock_toggle(args: argparse.Namespace) -> int:
|
|
1833
|
+
client = _build_client(args)
|
|
1834
|
+
_emit(client.post(NETWORK + "/rules/toggle", json_body={"id": args.id}), raw_json=args.json)
|
|
1835
|
+
return 0
|
|
1836
|
+
|
|
1837
|
+
|
|
1838
|
+
def _check_rule_ids(rules: List[Any]) -> None:
|
|
1839
|
+
"""Reject two rules with the same id. An app from protocol 1.11 rejects them too, but
|
|
1840
|
+
an older one keeps the first of the two, and loses the other without an error."""
|
|
1841
|
+
first: Dict[str, int] = {}
|
|
1842
|
+
for index, rule in enumerate(rules):
|
|
1843
|
+
rule_id = rule.get("id") if isinstance(rule, dict) else None
|
|
1844
|
+
if not isinstance(rule_id, str):
|
|
1845
|
+
continue
|
|
1846
|
+
if rule_id in first:
|
|
1847
|
+
raise UsageError(
|
|
1848
|
+
"rules {} and {} of the file have the same id {}: give each rule its own id, or none".format(
|
|
1849
|
+
first[rule_id], index, json.dumps(rule_id)
|
|
1850
|
+
)
|
|
1851
|
+
)
|
|
1852
|
+
first[rule_id] = index
|
|
1853
|
+
|
|
1854
|
+
|
|
1855
|
+
def cmd_mock_sync(args: argparse.Namespace) -> int:
|
|
1856
|
+
client = _build_client(args)
|
|
1857
|
+
try:
|
|
1858
|
+
with open(args.file, "r", encoding="utf-8") as fh:
|
|
1859
|
+
rules = json.load(fh)
|
|
1860
|
+
except (OSError, ValueError) as exc:
|
|
1861
|
+
print("could not read rules file {}: {}".format(args.file, exc), file=sys.stderr)
|
|
1862
|
+
return 2
|
|
1863
|
+
# `mock list --json` prints the rules in the envelope {"items": [...]}, so that its
|
|
1864
|
+
# output restores them. The app ignores the fields of a listed rule, such as hitCount.
|
|
1865
|
+
if isinstance(rules, dict) and isinstance(rules.get("items"), list):
|
|
1866
|
+
rules = rules["items"]
|
|
1867
|
+
if not isinstance(rules, list):
|
|
1868
|
+
print(
|
|
1869
|
+
"rules file must contain a JSON array of MockRuleInput objects, or the output of "
|
|
1870
|
+
"`lustro mock list --json`",
|
|
1871
|
+
file=sys.stderr,
|
|
1872
|
+
)
|
|
1873
|
+
return 2
|
|
1874
|
+
_check_rule_ids(rules)
|
|
1875
|
+
# `mock list --json` of a newer app has "failure": null in each rule, which an older app can ignore.
|
|
1876
|
+
if any(isinstance(rule, dict) and rule.get("failure") is not None for rule in rules):
|
|
1877
|
+
require_protocol(
|
|
1878
|
+
client, "mock sync", "failure", hint="update Lustro in the app, or leave failure out of the rules"
|
|
1879
|
+
)
|
|
1880
|
+
_emit(client.post(NETWORK + "/rules/_/sync", json_body=rules), raw_json=args.json)
|
|
1881
|
+
return 0
|
|
1882
|
+
|
|
1883
|
+
|
|
1884
|
+
# ── send ───────────────────────────────────────────────────────────────────────
|
|
1885
|
+
|
|
1886
|
+
|
|
1887
|
+
def cmd_senders(args: argparse.Namespace) -> int:
|
|
1888
|
+
client = _build_client(args)
|
|
1889
|
+
data = client.get(NETWORK + "/senders")
|
|
1890
|
+
if args.json:
|
|
1891
|
+
_emit(data, raw_json=True)
|
|
1892
|
+
return 0
|
|
1893
|
+
for index, sender in enumerate(data.get("items") or []):
|
|
1894
|
+
print(
|
|
1895
|
+
"{name} {base}{default}".format(
|
|
1896
|
+
name=sender.get("name"),
|
|
1897
|
+
base=sender.get("baseUrl") or "(absolute URLs only)",
|
|
1898
|
+
default=" (default)" if index == 0 else "",
|
|
1899
|
+
)
|
|
1900
|
+
)
|
|
1901
|
+
return 0
|
|
1902
|
+
|
|
1903
|
+
|
|
1904
|
+
def cmd_send(args: argparse.Namespace) -> int:
|
|
1905
|
+
client = _build_client(args)
|
|
1906
|
+
if args.sender is not None:
|
|
1907
|
+
require_protocol(client, "send", "--sender")
|
|
1908
|
+
payload: dict = {"url": args.url, "method": args.method}
|
|
1909
|
+
if args.sender is not None:
|
|
1910
|
+
payload["sender"] = args.sender
|
|
1911
|
+
if args.header:
|
|
1912
|
+
payload["headers"] = _parse_headers(args.header)
|
|
1913
|
+
if args.body is not None:
|
|
1914
|
+
payload["body"] = args.body
|
|
1915
|
+
_emit(client.post(NETWORK + "/send", json_body=payload), raw_json=args.json)
|
|
1916
|
+
return 0
|
|
1917
|
+
|
|
1918
|
+
|
|
1919
|
+
def cmd_mcp(args: argparse.Namespace) -> int:
|
|
1920
|
+
# Imported here: only this command needs the server, and the server reuses this module.
|
|
1921
|
+
from . import mcp
|
|
1922
|
+
|
|
1923
|
+
return mcp.serve(args)
|
|
1924
|
+
|
|
1925
|
+
|
|
1926
|
+
def _parse_headers(pairs: List[str]) -> dict:
|
|
1927
|
+
headers: dict = {}
|
|
1928
|
+
for pair in pairs:
|
|
1929
|
+
if ":" not in pair:
|
|
1930
|
+
raise SystemExit("invalid --header '{}': expected 'Key: value'".format(pair))
|
|
1931
|
+
key, _, value = pair.partition(":")
|
|
1932
|
+
headers[key.strip()] = value.strip()
|
|
1933
|
+
return headers
|
|
1934
|
+
|
|
1935
|
+
|
|
1936
|
+
# ── argparse wiring ────────────────────────────────────────────────────────────
|
|
1937
|
+
|
|
1938
|
+
|
|
1939
|
+
def _global_options() -> argparse.ArgumentParser:
|
|
1940
|
+
"""The flags that every command takes, before or after its name.
|
|
1941
|
+
|
|
1942
|
+
Every parser gets them, and each defaults to SUPPRESS: argparse copies a
|
|
1943
|
+
subcommand's parsed values over the values parsed before it, so a real
|
|
1944
|
+
default there would reset a flag given before the subcommand. main() sets
|
|
1945
|
+
the flags that no parser saw to GLOBAL_DEFAULTS.
|
|
1946
|
+
"""
|
|
1947
|
+
parent = argparse.ArgumentParser(add_help=False)
|
|
1948
|
+
group = parent.add_argument_group("global options (before or after the command)")
|
|
1949
|
+
group.add_argument("--host", default=argparse.SUPPRESS, help="server host (default {})".format(DEFAULT_HOST))
|
|
1950
|
+
group.add_argument(
|
|
1951
|
+
"--port", type=int, default=argparse.SUPPRESS, help="server port (default {})".format(DEFAULT_PORT)
|
|
1952
|
+
)
|
|
1953
|
+
group.add_argument("--token", default=argparse.SUPPRESS, help="bearer token (else $LUSTRO_TOKEN, else discovery)")
|
|
1954
|
+
group.add_argument("--device", default=argparse.SUPPRESS, metavar="SERIAL", help="adb device serial (adb -s)")
|
|
1955
|
+
group.add_argument("--package", default=argparse.SUPPRESS, help="app package id: discovery reads its prefs through run-as first, then its own log line")
|
|
1956
|
+
group.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="JSON output")
|
|
1957
|
+
return parent
|
|
1958
|
+
|
|
1959
|
+
|
|
1960
|
+
def _selection_options() -> argparse.ArgumentParser:
|
|
1961
|
+
"""Filters and --fields, for the commands that print transactions."""
|
|
1962
|
+
parent = argparse.ArgumentParser(add_help=False)
|
|
1963
|
+
filters = parent.add_argument_group("filters (they combine)")
|
|
1964
|
+
filters.add_argument(
|
|
1965
|
+
"--search",
|
|
1966
|
+
default=None,
|
|
1967
|
+
metavar="TEXT",
|
|
1968
|
+
help="the URL, the method, a header, or a body contains TEXT, ignoring case (on the server)",
|
|
1969
|
+
)
|
|
1970
|
+
filters.add_argument(
|
|
1971
|
+
"--regex",
|
|
1972
|
+
action="store_true",
|
|
1973
|
+
help="each word of --search TEXT is a Java regular expression, found ignoring case: all words must match, "
|
|
1974
|
+
"each in any field, and -word leaves out",
|
|
1975
|
+
)
|
|
1976
|
+
filters.add_argument("--url", default=None, metavar="TEXT", help="the URL contains TEXT (ignores case)")
|
|
1977
|
+
filters.add_argument("--method", default=None, help="the HTTP method, such as POST")
|
|
1978
|
+
filters.add_argument(
|
|
1979
|
+
"--status",
|
|
1980
|
+
type=_status_range,
|
|
1981
|
+
default=None,
|
|
1982
|
+
metavar="CODE",
|
|
1983
|
+
help="a status code such as 404, or a class such as 4xx",
|
|
1984
|
+
)
|
|
1985
|
+
filters.add_argument("--errors", action="store_true", help="status 400 or higher, or a failed request")
|
|
1986
|
+
output = parent.add_argument_group("output")
|
|
1987
|
+
output.add_argument(
|
|
1988
|
+
"--fields",
|
|
1989
|
+
type=_field_names,
|
|
1990
|
+
default=None,
|
|
1991
|
+
metavar="KEYS",
|
|
1992
|
+
help="print JSON Lines with only these keys, such as id,method,statusCode,url",
|
|
1993
|
+
)
|
|
1994
|
+
return parent
|
|
1995
|
+
|
|
1996
|
+
|
|
1997
|
+
def _fields_option() -> argparse.ArgumentParser:
|
|
1998
|
+
"""--fields, for the commands that print a list of other items."""
|
|
1999
|
+
parent = argparse.ArgumentParser(add_help=False)
|
|
2000
|
+
parent.add_argument_group("output").add_argument(
|
|
2001
|
+
"--fields",
|
|
2002
|
+
type=_field_names,
|
|
2003
|
+
default=None,
|
|
2004
|
+
metavar="KEYS",
|
|
2005
|
+
help="print JSON Lines with only these keys, such as id,state,url",
|
|
2006
|
+
)
|
|
2007
|
+
return parent
|
|
2008
|
+
|
|
2009
|
+
|
|
2010
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
2011
|
+
common = _global_options()
|
|
2012
|
+
selection = _selection_options()
|
|
2013
|
+
parser = argparse.ArgumentParser(
|
|
2014
|
+
prog="lustro",
|
|
2015
|
+
description="CLI client for the Lustro Android debug server (HTTP wire protocol).",
|
|
2016
|
+
parents=[common],
|
|
2017
|
+
)
|
|
2018
|
+
# Not action="version": that prints and exits as soon as argparse reads it, before a
|
|
2019
|
+
# --json after it. main() prints the version once all options are read.
|
|
2020
|
+
parser.add_argument(
|
|
2021
|
+
"--version",
|
|
2022
|
+
action="store_true",
|
|
2023
|
+
help="print the version of the CLI, the wire protocol that it implements, and its revision, and exit; "
|
|
2024
|
+
"with --json, as a JSON object",
|
|
2025
|
+
)
|
|
2026
|
+
|
|
2027
|
+
# Not required here, so that --version works without a command: main() requires it.
|
|
2028
|
+
sub = parser.add_subparsers(dest="command", metavar="<command>")
|
|
2029
|
+
|
|
2030
|
+
# open
|
|
2031
|
+
p_open = sub.add_parser("open", parents=[common], help="discover endpoint+token, adb-forward, open browser URL")
|
|
2032
|
+
p_open.add_argument(
|
|
2033
|
+
"--local-port",
|
|
2034
|
+
type=_port_number,
|
|
2035
|
+
default=None,
|
|
2036
|
+
metavar="N",
|
|
2037
|
+
help="forward local port N to the app's port; 0 lets adb choose a free port "
|
|
2038
|
+
"(default: the local port of an existing forward to the app, else the app's port)",
|
|
2039
|
+
)
|
|
2040
|
+
p_open.add_argument("--no-forward", action="store_true", help="skip `adb forward`")
|
|
2041
|
+
p_open.add_argument("--print-only", action="store_true", help="print the URL without opening a browser")
|
|
2042
|
+
p_open.set_defaults(func=cmd_open)
|
|
2043
|
+
|
|
2044
|
+
# meta
|
|
2045
|
+
p_meta = sub.add_parser("meta", parents=[common], help="GET /api/v1/_meta")
|
|
2046
|
+
p_meta.set_defaults(func=cmd_meta)
|
|
2047
|
+
|
|
2048
|
+
# ready
|
|
2049
|
+
p_ready = sub.add_parser(
|
|
2050
|
+
"ready",
|
|
2051
|
+
parents=[common],
|
|
2052
|
+
help="wait until the app's server answers, and print its endpoint",
|
|
2053
|
+
description="Wait until the app's server answers GET /api/v1/_meta, print the endpoint that the CLI "
|
|
2054
|
+
"reaches it at, and exit 0. Each try runs discovery again. At the timeout, print the cause and exit "
|
|
2055
|
+
"with its code: 3 no device, 4 the app of --package is not installed, 5 its build has no Lustro "
|
|
2056
|
+
"runtime, 6 it is not running or not in the foreground, its port does not answer, or another app's "
|
|
2057
|
+
"server holds its port. Pass --package so that the CLI checks your app, and not the app in the "
|
|
2058
|
+
"foreground.",
|
|
2059
|
+
)
|
|
2060
|
+
p_ready.add_argument(
|
|
2061
|
+
"--timeout",
|
|
2062
|
+
type=_positive_seconds,
|
|
2063
|
+
default=DEFAULT_READY_TIMEOUT,
|
|
2064
|
+
metavar="SECONDS",
|
|
2065
|
+
help="how long to wait (default {:g})".format(DEFAULT_READY_TIMEOUT),
|
|
2066
|
+
)
|
|
2067
|
+
p_ready.set_defaults(func=cmd_ready)
|
|
2068
|
+
|
|
2069
|
+
# schema [tabId]
|
|
2070
|
+
p_schema = sub.add_parser("schema", parents=[common], help="GET /api/v1/_schema or /api/v1/<tab>/_schema")
|
|
2071
|
+
p_schema.add_argument("tab_id", nargs="?", default=None, metavar="[tabId]")
|
|
2072
|
+
p_schema.set_defaults(func=cmd_schema)
|
|
2073
|
+
|
|
2074
|
+
# api METHOD PATH
|
|
2075
|
+
p_api = sub.add_parser(
|
|
2076
|
+
"api",
|
|
2077
|
+
parents=[common],
|
|
2078
|
+
help="send a request to any route, such as a tab's, and print the response",
|
|
2079
|
+
description="Send one request to any route of the app, with the token and the port that the other "
|
|
2080
|
+
"commands use, and print the response body: JSON as JSON, any other body as it is. A PATH without a "
|
|
2081
|
+
"leading / is relative to /api/v1/, so network/transactions is /api/v1/network/transactions. For an error "
|
|
2082
|
+
"response, it prints the error from the error envelope on stderr and exits 1, or 2 when the app rejects a "
|
|
2083
|
+
"search. `lustro schema <tabId>` prints the OpenAPI document of a tab, which describes its routes.",
|
|
2084
|
+
)
|
|
2085
|
+
p_api.add_argument("method", type=_http_method, metavar="METHOD", help="GET, POST, or another HTTP method")
|
|
2086
|
+
p_api.add_argument("path", metavar="PATH", help="such as /api/v1/network/transactions or network/transactions")
|
|
2087
|
+
p_api.add_argument(
|
|
2088
|
+
"--param",
|
|
2089
|
+
type=_param_pair,
|
|
2090
|
+
action="append",
|
|
2091
|
+
default=None,
|
|
2092
|
+
metavar="KEY=VALUE",
|
|
2093
|
+
help="a query parameter (repeatable), added to a query in PATH",
|
|
2094
|
+
)
|
|
2095
|
+
api_body = p_api.add_mutually_exclusive_group()
|
|
2096
|
+
api_body.add_argument("--body", default=None, metavar="JSON", help="the JSON request body")
|
|
2097
|
+
api_body.add_argument(
|
|
2098
|
+
"--input", default=None, metavar="FILE", help="read the JSON request body from FILE, or from stdin for -"
|
|
2099
|
+
)
|
|
2100
|
+
p_api.set_defaults(func=cmd_api)
|
|
2101
|
+
|
|
2102
|
+
# net ...
|
|
2103
|
+
p_net = sub.add_parser("net", parents=[common], help="network tab operations")
|
|
2104
|
+
net_sub = p_net.add_subparsers(dest="net_command", metavar="<op>")
|
|
2105
|
+
net_sub.required = True
|
|
2106
|
+
|
|
2107
|
+
n_list = net_sub.add_parser(
|
|
2108
|
+
"list", parents=[common, selection], help="the newest transactions, newest first (GET transactions)"
|
|
2109
|
+
)
|
|
2110
|
+
rows = n_list.add_mutually_exclusive_group()
|
|
2111
|
+
rows.add_argument(
|
|
2112
|
+
"--last",
|
|
2113
|
+
type=_whole_number(1),
|
|
2114
|
+
default=DEFAULT_LAST,
|
|
2115
|
+
metavar="N",
|
|
2116
|
+
help="print the newest N (default {})".format(DEFAULT_LAST),
|
|
2117
|
+
)
|
|
2118
|
+
rows.add_argument("--all", action="store_true", help="print every transaction")
|
|
2119
|
+
n_list.set_defaults(func=cmd_net_list)
|
|
2120
|
+
|
|
2121
|
+
n_state = net_sub.add_parser(
|
|
2122
|
+
"state", parents=[common], help="capture state: paused, overwrite mode, throttle, capture filter"
|
|
2123
|
+
)
|
|
2124
|
+
n_state.set_defaults(func=cmd_net_state)
|
|
2125
|
+
|
|
2126
|
+
n_poll = net_sub.add_parser(
|
|
2127
|
+
"poll",
|
|
2128
|
+
parents=[common, selection],
|
|
2129
|
+
help="cursor loop: print transactions as they come, and again when they finish",
|
|
2130
|
+
)
|
|
2131
|
+
n_poll.add_argument(
|
|
2132
|
+
"--interval", type=_positive_seconds, default=1.0, metavar="SECONDS", help="seconds between polls (default 1)"
|
|
2133
|
+
)
|
|
2134
|
+
n_poll.add_argument("--once", action="store_true", help="single poll then exit")
|
|
2135
|
+
n_poll.set_defaults(func=cmd_net_poll)
|
|
2136
|
+
|
|
2137
|
+
n_wait = net_sub.add_parser(
|
|
2138
|
+
"wait",
|
|
2139
|
+
parents=[common, selection],
|
|
2140
|
+
help="wait until a matching request finishes, print it, and exit",
|
|
2141
|
+
description="Wait until a matching request finishes, print it, and exit 0; exit 1 at the timeout. "
|
|
2142
|
+
"Requests that finished before wait started don't count, so start it before the action that sends "
|
|
2143
|
+
"the request, or give that action after --: wait then runs it after it reads the list.",
|
|
2144
|
+
)
|
|
2145
|
+
n_wait.add_argument(
|
|
2146
|
+
"--timeout", type=_positive_seconds, default=30.0, metavar="SECONDS", help="exit 1 after this time (default 30)"
|
|
2147
|
+
)
|
|
2148
|
+
n_wait.add_argument(
|
|
2149
|
+
"--interval", type=_positive_seconds, default=0.5, metavar="SECONDS", help="seconds between polls (default 0.5)"
|
|
2150
|
+
)
|
|
2151
|
+
n_wait.add_argument(
|
|
2152
|
+
"action",
|
|
2153
|
+
nargs="*",
|
|
2154
|
+
metavar="-- COMMAND",
|
|
2155
|
+
help="a command that makes the app send the request, run after the first poll",
|
|
2156
|
+
)
|
|
2157
|
+
n_wait.set_defaults(func=cmd_net_wait)
|
|
2158
|
+
|
|
2159
|
+
n_get = net_sub.add_parser("get", parents=[common], help="GET transactions/<id>, with long bodies cut")
|
|
2160
|
+
n_get.add_argument("id", help=ID_HELP)
|
|
2161
|
+
bodies = n_get.add_mutually_exclusive_group()
|
|
2162
|
+
bodies.add_argument(
|
|
2163
|
+
"--max-body",
|
|
2164
|
+
type=_whole_number(0),
|
|
2165
|
+
default=DEFAULT_MAX_BODY,
|
|
2166
|
+
metavar="BYTES",
|
|
2167
|
+
help="cut each body after BYTES (default {})".format(DEFAULT_MAX_BODY),
|
|
2168
|
+
)
|
|
2169
|
+
bodies.add_argument("--no-body", action="store_true", help="leave the bodies out")
|
|
2170
|
+
bodies.add_argument("--full", action="store_true", help="print the bodies whole")
|
|
2171
|
+
n_get.set_defaults(func=cmd_net_get)
|
|
2172
|
+
|
|
2173
|
+
n_body = net_sub.add_parser(
|
|
2174
|
+
"body",
|
|
2175
|
+
parents=[common],
|
|
2176
|
+
help="GET transactions/<id>/body/<direction>: save a captured body as it is stored",
|
|
2177
|
+
)
|
|
2178
|
+
n_body.add_argument("id", help=ID_HELP)
|
|
2179
|
+
n_body.add_argument(
|
|
2180
|
+
"direction", nargs="?", default="response", choices=["request", "response"], help="default: response"
|
|
2181
|
+
)
|
|
2182
|
+
n_body.add_argument("-o", "--output", default=None, metavar="FILE", help="write the body to FILE (default: stdout)")
|
|
2183
|
+
n_body.set_defaults(func=cmd_net_body)
|
|
2184
|
+
|
|
2185
|
+
n_export = net_sub.add_parser(
|
|
2186
|
+
"export",
|
|
2187
|
+
parents=[common],
|
|
2188
|
+
help="GET transactions/_/export: save transactions as a HAR file",
|
|
2189
|
+
description="Save the captured transactions as a HAR 1.2 file, which browser devtools and HTTP tools "
|
|
2190
|
+
"import. Headers and bodies are redacted as in the app. Each entry has the transaction id, and what HAR "
|
|
2191
|
+
"has no field for, in _lustro.",
|
|
2192
|
+
)
|
|
2193
|
+
n_export.add_argument(
|
|
2194
|
+
"--har", required=True, metavar="FILE", help="write the HAR document to FILE, or to stdout for -"
|
|
2195
|
+
)
|
|
2196
|
+
n_export.add_argument(
|
|
2197
|
+
"--ids",
|
|
2198
|
+
nargs="+",
|
|
2199
|
+
type=_id_list,
|
|
2200
|
+
default=None,
|
|
2201
|
+
metavar="ID",
|
|
2202
|
+
help="only these transactions, separated by spaces or commas; each is {} (default: every one)".format(ID_HELP),
|
|
2203
|
+
)
|
|
2204
|
+
n_export.set_defaults(func=cmd_net_export)
|
|
2205
|
+
|
|
2206
|
+
n_ws = net_sub.add_parser(
|
|
2207
|
+
"ws",
|
|
2208
|
+
parents=[common],
|
|
2209
|
+
help="WebSocket connections and their messages",
|
|
2210
|
+
description="Inspect the WebSockets that the app creates with the factory from Lustro.webSocketFactory. "
|
|
2211
|
+
"A socket that the app creates in another way shows only its handshake, in `lustro net list`.",
|
|
2212
|
+
)
|
|
2213
|
+
ws_sub = n_ws.add_subparsers(dest="ws_command", metavar="<op>")
|
|
2214
|
+
ws_sub.required = True
|
|
2215
|
+
fields = _fields_option()
|
|
2216
|
+
|
|
2217
|
+
w_list = ws_sub.add_parser("list", parents=[common, fields], help="the connections, newest first (GET websockets)")
|
|
2218
|
+
w_list.set_defaults(func=cmd_net_ws_list)
|
|
2219
|
+
|
|
2220
|
+
w_get = ws_sub.add_parser(
|
|
2221
|
+
"get", parents=[common], help="GET websockets/<id>: one connection, with the headers of its handshake"
|
|
2222
|
+
)
|
|
2223
|
+
w_get.add_argument("id", help=WS_ID_HELP)
|
|
2224
|
+
w_get.set_defaults(func=cmd_net_ws_get)
|
|
2225
|
+
|
|
2226
|
+
w_events = ws_sub.add_parser(
|
|
2227
|
+
"events",
|
|
2228
|
+
parents=[common, fields],
|
|
2229
|
+
help="GET websockets/<id>/events: a connection's messages and lifecycle events, oldest first",
|
|
2230
|
+
description="Print a connection's log, oldest first: each message with its direction, type, size, and the "
|
|
2231
|
+
"start of its payload, and each lifecycle event. `->` is a message the app sent. OkHttp queued it, which "
|
|
2232
|
+
"does not show that the server received it.",
|
|
2233
|
+
)
|
|
2234
|
+
w_events.add_argument("id", help=WS_ID_HELP)
|
|
2235
|
+
event_rows = w_events.add_mutually_exclusive_group()
|
|
2236
|
+
event_rows.add_argument(
|
|
2237
|
+
"--last",
|
|
2238
|
+
type=_whole_number(1),
|
|
2239
|
+
default=DEFAULT_LAST,
|
|
2240
|
+
metavar="N",
|
|
2241
|
+
help="print the last N (default {})".format(DEFAULT_LAST),
|
|
2242
|
+
)
|
|
2243
|
+
event_rows.add_argument("--all", action="store_true", help="print every event the log has")
|
|
2244
|
+
event_direction = w_events.add_mutually_exclusive_group()
|
|
2245
|
+
event_direction.add_argument("--sent", action="store_true", help="only what the app sent")
|
|
2246
|
+
event_direction.add_argument("--received", action="store_true", help="only what the app received")
|
|
2247
|
+
w_events.add_argument(
|
|
2248
|
+
"--search", default=None, metavar="TEXT", help="only the text messages that contain TEXT (on the server)"
|
|
2249
|
+
)
|
|
2250
|
+
w_events.add_argument(
|
|
2251
|
+
"--regex",
|
|
2252
|
+
action="store_true",
|
|
2253
|
+
help="each word of --search TEXT is a Java regular expression, found ignoring case: all words must match, "
|
|
2254
|
+
"and -word leaves out",
|
|
2255
|
+
)
|
|
2256
|
+
w_events.add_argument("--follow", action="store_true", help="then print each new event as it comes, until Ctrl-C")
|
|
2257
|
+
w_events.add_argument(
|
|
2258
|
+
"--interval",
|
|
2259
|
+
type=_positive_seconds,
|
|
2260
|
+
default=1.0,
|
|
2261
|
+
metavar="SECONDS",
|
|
2262
|
+
help="with --follow: seconds between polls (default 1)",
|
|
2263
|
+
)
|
|
2264
|
+
w_events.set_defaults(func=cmd_net_ws_events)
|
|
2265
|
+
|
|
2266
|
+
w_payload = ws_sub.add_parser(
|
|
2267
|
+
"payload",
|
|
2268
|
+
parents=[common],
|
|
2269
|
+
help="GET websockets/<id>/events/<seq>/payload: save one message's payload as it is stored",
|
|
2270
|
+
)
|
|
2271
|
+
w_payload.add_argument("id", help=WS_ID_HELP)
|
|
2272
|
+
w_payload.add_argument("seq", type=_whole_number(1), help="the message's seq, the first column of `net ws events`")
|
|
2273
|
+
w_payload.add_argument(
|
|
2274
|
+
"-o", "--output", default=None, metavar="FILE", help="write the payload to FILE (default: stdout)"
|
|
2275
|
+
)
|
|
2276
|
+
w_payload.set_defaults(func=cmd_net_ws_payload)
|
|
2277
|
+
|
|
2278
|
+
n_clear = net_sub.add_parser("clear", parents=[common], help="POST clear (transactions and WebSocket connections)")
|
|
2279
|
+
n_clear.set_defaults(func=cmd_net_clear)
|
|
2280
|
+
|
|
2281
|
+
n_pause = net_sub.add_parser("pause", parents=[common], help="POST pause (toggle capture-only pause)")
|
|
2282
|
+
n_pause.set_defaults(func=cmd_net_pause)
|
|
2283
|
+
|
|
2284
|
+
n_overwrite = net_sub.add_parser("overwrite", parents=[common], help="POST overwrite-mode (toggle)")
|
|
2285
|
+
n_overwrite.set_defaults(func=cmd_net_overwrite)
|
|
2286
|
+
|
|
2287
|
+
n_throttle = net_sub.add_parser("throttle", parents=[common], help="POST throttle <ms>")
|
|
2288
|
+
n_throttle.add_argument("ms", type=int, help="delay in ms, from 0 (off) to 600000 (10 minutes)")
|
|
2289
|
+
n_throttle.set_defaults(func=cmd_net_throttle)
|
|
2290
|
+
|
|
2291
|
+
# mock ...
|
|
2292
|
+
p_mock = sub.add_parser("mock", parents=[common], help="mock rule operations")
|
|
2293
|
+
mock_sub = p_mock.add_subparsers(dest="mock_command", metavar="<op>")
|
|
2294
|
+
mock_sub.required = True
|
|
2295
|
+
|
|
2296
|
+
m_list = mock_sub.add_parser("list", parents=[common], help="GET rules")
|
|
2297
|
+
m_list.set_defaults(func=cmd_mock_list)
|
|
2298
|
+
|
|
2299
|
+
m_add = mock_sub.add_parser("add", parents=[common], help="POST rules (add/upsert)")
|
|
2300
|
+
m_add.add_argument("--url-pattern", required=True, dest="url_pattern", help="looked for anywhere in the URL: a substring, or a regex with the regex: prefix")
|
|
2301
|
+
m_add.add_argument("--id", default=None, help="stable id (makes the write idempotent/upsert)")
|
|
2302
|
+
m_add.add_argument("--name", default=None)
|
|
2303
|
+
m_add.add_argument("--method", default=None, help="HTTP method to match (omit = any)")
|
|
2304
|
+
m_add.add_argument("--status", type=int, default=None, help="mocked response status code")
|
|
2305
|
+
m_add.add_argument("--body", default=None, help="mocked response body")
|
|
2306
|
+
m_add.add_argument("--header", action="append", metavar="K:V", help="response header (repeatable)")
|
|
2307
|
+
# Not argparse choices: the app checks the name, and a newer app can know more.
|
|
2308
|
+
m_add.add_argument(
|
|
2309
|
+
"--failure",
|
|
2310
|
+
default=None,
|
|
2311
|
+
metavar="NAME",
|
|
2312
|
+
help="fail the request with a connection error instead of a response: "
|
|
2313
|
+
+ ", ".join(MOCK_FAILURES),
|
|
2314
|
+
)
|
|
2315
|
+
m_add.set_defaults(func=cmd_mock_add)
|
|
2316
|
+
|
|
2317
|
+
m_delete = mock_sub.add_parser("delete", parents=[common], help="POST rules/delete <id>")
|
|
2318
|
+
m_delete.add_argument("id")
|
|
2319
|
+
m_delete.set_defaults(func=cmd_mock_delete)
|
|
2320
|
+
|
|
2321
|
+
m_toggle = mock_sub.add_parser("toggle", parents=[common], help="POST rules/toggle <id>")
|
|
2322
|
+
m_toggle.add_argument("id")
|
|
2323
|
+
m_toggle.set_defaults(func=cmd_mock_toggle)
|
|
2324
|
+
|
|
2325
|
+
m_sync = mock_sub.add_parser(
|
|
2326
|
+
"sync",
|
|
2327
|
+
parents=[common],
|
|
2328
|
+
help="POST rules/_/sync <file.json> (atomic replace)",
|
|
2329
|
+
description="Replace every mock rule with the rules in the file, in one step. The file has a JSON array of "
|
|
2330
|
+
"MockRuleInput objects, or the output of `lustro mock list --json`, so a test can save the rules and restore "
|
|
2331
|
+
"them after: `lustro mock list --json > rules.json`, change the rules, then `lustro mock sync rules.json`.",
|
|
2332
|
+
)
|
|
2333
|
+
m_sync.add_argument(
|
|
2334
|
+
"file", help="path to a JSON array of MockRuleInput objects, or to the output of `lustro mock list --json`"
|
|
2335
|
+
)
|
|
2336
|
+
m_sync.set_defaults(func=cmd_mock_sync)
|
|
2337
|
+
|
|
2338
|
+
# screen ...
|
|
2339
|
+
p_screen = sub.add_parser("screen", parents=[common], help="the app's windows and UI tree (Screen tab)")
|
|
2340
|
+
screen_sub = p_screen.add_subparsers(dest="screen_command", metavar="<op>")
|
|
2341
|
+
screen_sub.required = True
|
|
2342
|
+
s_tree = screen_sub.add_parser(
|
|
2343
|
+
"tree",
|
|
2344
|
+
parents=[common],
|
|
2345
|
+
help="GET screen/tree: each window of the app, and the nodes on screen that have a text, tag, role, action, or state",
|
|
2346
|
+
description="Print each window of the app and its nodes, one line each: the id, the role or class, the text, "
|
|
2347
|
+
"the test tag, the states and actions, and the visible bounds on the screen in uiautomator's format. "
|
|
2348
|
+
"Without --all, only the nodes on the screen that have a text, a tag, a role, an action, or a state. "
|
|
2349
|
+
"--json prints the whole response. A script that reads the tree often should send the GET itself, with "
|
|
2350
|
+
"the token and the forward that it keeps, instead of starting this command for each read.",
|
|
2351
|
+
)
|
|
2352
|
+
s_tree.add_argument("--unmerged", action="store_true", help="the unmerged semantics tree: each text in a node of its own")
|
|
2353
|
+
s_tree.add_argument(
|
|
2354
|
+
"--settle",
|
|
2355
|
+
type=_settle_ms,
|
|
2356
|
+
default=0,
|
|
2357
|
+
metavar="MS",
|
|
2358
|
+
help="read on each frame until two reads in a row are the same, for up to MS milliseconds",
|
|
2359
|
+
)
|
|
2360
|
+
s_tree.add_argument("--all", action="store_true", help="every node, also the containers and the nodes that are not on the screen")
|
|
2361
|
+
s_tree.set_defaults(func=cmd_screen_tree)
|
|
2362
|
+
|
|
2363
|
+
# send
|
|
2364
|
+
p_senders = sub.add_parser("senders", parents=[common], help="GET senders (the clients send can use; the first is the default)")
|
|
2365
|
+
p_senders.set_defaults(func=cmd_senders)
|
|
2366
|
+
|
|
2367
|
+
p_send = sub.add_parser("send", parents=[common], help="POST send (synchronous, through one of the app's senders)")
|
|
2368
|
+
p_send.add_argument("--url", required=True, help="absolute URL, or a path appended to the sender's base URL")
|
|
2369
|
+
p_send.add_argument("--sender", default=None, metavar="NAME", help="name of a sender from 'lustro senders' (default: the first)")
|
|
2370
|
+
p_send.add_argument("--method", default="GET")
|
|
2371
|
+
p_send.add_argument("--header", action="append", metavar="K:V", help="request header (repeatable)")
|
|
2372
|
+
p_send.add_argument("--body", default=None, help="request body")
|
|
2373
|
+
p_send.set_defaults(func=cmd_send)
|
|
2374
|
+
|
|
2375
|
+
# mcp
|
|
2376
|
+
p_mcp = sub.add_parser(
|
|
2377
|
+
"mcp",
|
|
2378
|
+
parents=[common],
|
|
2379
|
+
help="run an MCP server on stdin and stdout, for agents that can only call MCP tools",
|
|
2380
|
+
description="Run a Model Context Protocol server on stdin and stdout, for an agent that can only call "
|
|
2381
|
+
"MCP tools, such as Claude Desktop. The agent's client starts this command "
|
|
2382
|
+
"when a session starts and stops it at the end; add it to the client's MCP config as "
|
|
2383
|
+
'{"command": "lustro", "args": ["mcp"]}. Each tool call finds the app as the other commands do, so '
|
|
2384
|
+
"--device, --package, --port, and --token apply to every call. An agent that can run shell commands "
|
|
2385
|
+
"should run the other commands instead: a command costs context only when the agent runs it.",
|
|
2386
|
+
)
|
|
2387
|
+
p_mcp.set_defaults(func=cmd_mcp)
|
|
2388
|
+
|
|
2389
|
+
return parser
|
|
2390
|
+
|
|
2391
|
+
|
|
2392
|
+
def _join_search_values(argv: List[str]) -> List[str]:
|
|
2393
|
+
"""Join --search and its value, so that argparse takes text that starts with
|
|
2394
|
+
one minus, such as ``-1``, as the value instead of an option. A value that
|
|
2395
|
+
starts with two, such as ``--json`` or ``--``, is left to argparse, which
|
|
2396
|
+
says that --search has no value."""
|
|
2397
|
+
joined: List[str] = []
|
|
2398
|
+
i = 0
|
|
2399
|
+
while i < len(argv):
|
|
2400
|
+
nxt = argv[i + 1] if i + 1 < len(argv) else ""
|
|
2401
|
+
if argv[i] == "--search" and nxt.startswith("-") and not nxt.startswith("--"):
|
|
2402
|
+
joined.append("--search=" + argv[i + 1])
|
|
2403
|
+
i += 2
|
|
2404
|
+
continue
|
|
2405
|
+
if argv[i] == "--":
|
|
2406
|
+
# What follows is net wait's action command, not ours to read.
|
|
2407
|
+
joined.extend(argv[i:])
|
|
2408
|
+
break
|
|
2409
|
+
joined.append(argv[i])
|
|
2410
|
+
i += 1
|
|
2411
|
+
return joined
|
|
2412
|
+
|
|
2413
|
+
|
|
2414
|
+
def version_info() -> Dict[str, Any]:
|
|
2415
|
+
"""What ``lustro --version --json`` prints."""
|
|
2416
|
+
return {"version": __version__, "protocol": PROTOCOL_VERSION, "revision": REVISION}
|
|
2417
|
+
|
|
2418
|
+
|
|
2419
|
+
def version_line() -> str:
|
|
2420
|
+
return "lustro {} (protocol {}, revision {})".format(__version__, PROTOCOL_VERSION, REVISION)
|
|
2421
|
+
|
|
2422
|
+
|
|
2423
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
2424
|
+
parser = build_parser()
|
|
2425
|
+
args = parser.parse_args(_join_search_values(sys.argv[1:] if argv is None else list(argv)))
|
|
2426
|
+
if args.version:
|
|
2427
|
+
if getattr(args, "json", False):
|
|
2428
|
+
_emit(version_info(), raw_json=True)
|
|
2429
|
+
else:
|
|
2430
|
+
print(version_line())
|
|
2431
|
+
return exitcodes.OK
|
|
2432
|
+
if args.command is None:
|
|
2433
|
+
parser.error("the following arguments are required: <command>")
|
|
2434
|
+
if getattr(args, "regex", False) and not getattr(args, "search", None):
|
|
2435
|
+
parser.error("--regex makes --search TEXT a regular expression, so it needs --search")
|
|
2436
|
+
for name, default in GLOBAL_DEFAULTS.items():
|
|
2437
|
+
if not hasattr(args, name):
|
|
2438
|
+
setattr(args, name, default)
|
|
2439
|
+
try:
|
|
2440
|
+
code = args.func(args)
|
|
2441
|
+
# Flush here, not at exit, so that a reader that closed the pipe early
|
|
2442
|
+
# reaches the BrokenPipeError handler below.
|
|
2443
|
+
sys.stdout.flush()
|
|
2444
|
+
return code
|
|
2445
|
+
except (UsageError, DiscoveryError, LustroError) as exc:
|
|
2446
|
+
code, message = failure(args, exc)
|
|
2447
|
+
print("error: {}".format(message), file=sys.stderr)
|
|
2448
|
+
return code
|
|
2449
|
+
except BrokenPipeError:
|
|
2450
|
+
# The reader closed the pipe early, as `head` does. Send the rest of the
|
|
2451
|
+
# output to devnull, so that the flush at exit doesn't fail again.
|
|
2452
|
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
2453
|
+
os.dup2(devnull, sys.stdout.fileno())
|
|
2454
|
+
return 1
|
|
2455
|
+
except KeyboardInterrupt:
|
|
2456
|
+
return 130
|
|
2457
|
+
|
|
2458
|
+
|
|
2459
|
+
if __name__ == "__main__": # pragma: no cover
|
|
2460
|
+
sys.exit(main())
|