orangehack 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.
- orangehack/__init__.py +15 -0
- orangehack/__main__.py +3 -0
- orangehack/client.py +239 -0
- orangehack/commands/__init__.py +1 -0
- orangehack/commands/api.py +347 -0
- orangehack/commands/attempts.py +253 -0
- orangehack/commands/auth.py +224 -0
- orangehack/commands/competitions.py +215 -0
- orangehack/commands/download.py +145 -0
- orangehack/commands/leaderboard.py +114 -0
- orangehack/commands/submit.py +372 -0
- orangehack/config.py +221 -0
- orangehack/errors.py +109 -0
- orangehack/main.py +98 -0
- orangehack/output.py +105 -0
- orangehack/resolve.py +172 -0
- orangehack/session.py +127 -0
- orangehack/transfer.py +442 -0
- orangehack/version_check.py +104 -0
- orangehack-0.1.0.dist-info/METADATA +145 -0
- orangehack-0.1.0.dist-info/RECORD +23 -0
- orangehack-0.1.0.dist-info/WHEEL +4 -0
- orangehack-0.1.0.dist-info/entry_points.txt +2 -0
orangehack/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""The official command-line client of the OrangeHack platform."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("orangehack")
|
|
7
|
+
except PackageNotFoundError: # running from a source tree that was never installed
|
|
8
|
+
__version__ = "0.0.0"
|
|
9
|
+
|
|
10
|
+
CLIENT_HEADER = "X-OrangeHack-Client"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def client_value() -> str:
|
|
14
|
+
"""What `submission-channels` reads to record an attempt with source `cli`."""
|
|
15
|
+
return f"orangehack-cli/{__version__}"
|
orangehack/__main__.py
ADDED
orangehack/client.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""The HTTP client: base address, the token, the client header, retries and error mapping.
|
|
2
|
+
|
|
3
|
+
Retries (exponential backoff with jitter, 0.5 s … 8 s) cover connection errors, 502, 503 (except
|
|
4
|
+
`channel_unavailable`), 504 and 429 (waiting `Retry-After`, at most 60 s). A request marked
|
|
5
|
+
`once=True` (the hand-in itself) is never sent twice: a connection that broke after it was sent, any
|
|
6
|
+
5xx answer (except `channel_unavailable`) and a 2xx answer that is not JSON raise `LostAnswer`, and
|
|
7
|
+
the caller reads the history instead.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import random
|
|
13
|
+
import ssl
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
from . import CLIENT_HEADER, __version__, client_value
|
|
22
|
+
from .config import LOCAL_HOSTS
|
|
23
|
+
from .errors import ApiError, CliError, Exit, LostAnswer, from_api
|
|
24
|
+
|
|
25
|
+
DELAYS = (0.5, 1.0, 2.0, 4.0, 8.0)
|
|
26
|
+
MAX_RETRY_AFTER = 60.0
|
|
27
|
+
RETRY_STATUS = {502, 503, 504, 429}
|
|
28
|
+
TIMEOUT = httpx.Timeout(60.0, connect=15.0)
|
|
29
|
+
# Errors raised before a byte of the request left: safe to resend even a hand-in.
|
|
30
|
+
NOT_SENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
|
|
31
|
+
# A platform on this machine is reached directly: neither HTTP(S)_PROXY nor --proxy ever sees its
|
|
32
|
+
# requests, so the token of a local platform never leaves the machine through a proxy. Other loopback
|
|
33
|
+
# spellings (127.0.0.2, 0.0.0.0) are refused for http:// by `config.checked_url`, and over https://
|
|
34
|
+
# a proxy sees only CONNECT.
|
|
35
|
+
DIRECT = {f"all://[{host}]" if ":" in host else f"all://{host}": None for host in LOCAL_HOSTS}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _redact(headers: httpx.Headers) -> dict[str, str]:
|
|
39
|
+
return {
|
|
40
|
+
name: ("<скрыт>" if name.lower() in ("authorization", "cookie") else value)
|
|
41
|
+
for name, value in headers.items()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def error_of(response: httpx.Response) -> ApiError:
|
|
46
|
+
body: dict[str, Any] = {}
|
|
47
|
+
try:
|
|
48
|
+
parsed = response.json()
|
|
49
|
+
if isinstance(parsed, dict):
|
|
50
|
+
body = parsed
|
|
51
|
+
except ValueError:
|
|
52
|
+
pass
|
|
53
|
+
code = str(body.get("code", "")) or f"http_{response.status_code}"
|
|
54
|
+
detail = str(body.get("detail", "")) if body.get("detail") is not None else ""
|
|
55
|
+
return ApiError(response.status_code, code, detail, body)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _context(ca_bundle: str) -> ssl.SSLContext:
|
|
59
|
+
try:
|
|
60
|
+
return ssl.create_default_context(cafile=ca_bundle)
|
|
61
|
+
except (OSError, ssl.SSLError) as exc:
|
|
62
|
+
raise CliError(
|
|
63
|
+
Exit.USAGE,
|
|
64
|
+
f"Не удалось прочитать файл сертификатов {ca_bundle}.",
|
|
65
|
+
"Проверьте путь в --ca-bundle или ORANGEHACK_CA_BUNDLE: нужен файл PEM.",
|
|
66
|
+
code="ca_bundle",
|
|
67
|
+
) from exc
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Client:
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
base_url: str,
|
|
74
|
+
token: str = "",
|
|
75
|
+
*,
|
|
76
|
+
proxy: str | None = None,
|
|
77
|
+
ca_bundle: str | None = None,
|
|
78
|
+
verbose: bool = False,
|
|
79
|
+
transport: httpx.BaseTransport | None = None,
|
|
80
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
81
|
+
) -> None:
|
|
82
|
+
self.base_url = base_url.rstrip("/")
|
|
83
|
+
self.token = token
|
|
84
|
+
self.verbose = verbose
|
|
85
|
+
self.sleep = sleep
|
|
86
|
+
verify: Any = _context(ca_bundle) if ca_bundle else True
|
|
87
|
+
options: dict[str, Any] = {
|
|
88
|
+
"timeout": TIMEOUT,
|
|
89
|
+
"verify": verify,
|
|
90
|
+
"follow_redirects": True,
|
|
91
|
+
"mounts": DIRECT,
|
|
92
|
+
}
|
|
93
|
+
if proxy:
|
|
94
|
+
options["proxy"] = proxy
|
|
95
|
+
if transport is not None:
|
|
96
|
+
options["transport"] = transport
|
|
97
|
+
# trust_env (the default) honours HTTPS_PROXY, NO_PROXY and SSL_CERT_FILE; DIRECT wins over both proxies.
|
|
98
|
+
self._http = httpx.Client(
|
|
99
|
+
base_url=self.base_url,
|
|
100
|
+
headers={CLIENT_HEADER: client_value(), "User-Agent": f"orangehack-cli/{__version__}"},
|
|
101
|
+
**options,
|
|
102
|
+
)
|
|
103
|
+
# Signed storage addresses get neither the token nor the client header; --verbose shows
|
|
104
|
+
# them without the query, which holds the signature.
|
|
105
|
+
hooks = {"response": [self._log_storage]} if verbose else {}
|
|
106
|
+
self._storage = httpx.Client(event_hooks=hooks, **options)
|
|
107
|
+
|
|
108
|
+
def close(self) -> None:
|
|
109
|
+
self._http.close()
|
|
110
|
+
self._storage.close()
|
|
111
|
+
|
|
112
|
+
# --- logging ---------------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
def _log(self, request: httpx.Request, response: httpx.Response | None, note: str = "") -> None:
|
|
115
|
+
if not self.verbose:
|
|
116
|
+
return
|
|
117
|
+
status = response.status_code if response is not None else "-"
|
|
118
|
+
address = str(request.url)
|
|
119
|
+
if self.token: # `orangehack api` sends PATH as given, and a person may put the token there
|
|
120
|
+
address = address.replace(self.token, "<скрыт>")
|
|
121
|
+
print(f"> {request.method} {address} -> {status} {note}".rstrip(), file=sys.stderr)
|
|
122
|
+
print(f" {_redact(request.headers)}", file=sys.stderr)
|
|
123
|
+
|
|
124
|
+
def _log_storage(self, response: httpx.Response) -> None:
|
|
125
|
+
request = response.request
|
|
126
|
+
address = request.url.copy_with(query=None, fragment=None)
|
|
127
|
+
print(f"> {request.method} {address} -> {response.status_code}", file=sys.stderr)
|
|
128
|
+
|
|
129
|
+
# --- retries ---------------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
def _wait(self, attempt: int, response: httpx.Response | None) -> None:
|
|
132
|
+
delay = DELAYS[attempt]
|
|
133
|
+
if response is not None and response.status_code == 429:
|
|
134
|
+
header = response.headers.get("Retry-After", "")
|
|
135
|
+
try:
|
|
136
|
+
delay = min(float(header), MAX_RETRY_AFTER)
|
|
137
|
+
except ValueError:
|
|
138
|
+
pass
|
|
139
|
+
else:
|
|
140
|
+
self.sleep(delay)
|
|
141
|
+
return
|
|
142
|
+
self.sleep(delay * (1 + random.random() / 2))
|
|
143
|
+
|
|
144
|
+
def send(
|
|
145
|
+
self,
|
|
146
|
+
method: str,
|
|
147
|
+
path: str,
|
|
148
|
+
*,
|
|
149
|
+
auth: bool = True,
|
|
150
|
+
once: bool = False,
|
|
151
|
+
storage: bool = False,
|
|
152
|
+
retries: bool = True,
|
|
153
|
+
raw: bool = False,
|
|
154
|
+
**kwargs: Any,
|
|
155
|
+
) -> httpx.Response:
|
|
156
|
+
"""Send with retries; returns a 2xx (or a 206/416 for ranges) or raises.
|
|
157
|
+
|
|
158
|
+
`retries=False` sends once (the version check, which must never hold a command up).
|
|
159
|
+
`raw=True` (`orangehack api`) returns the last answer of any status and never follows a
|
|
160
|
+
redirect, so the token cannot travel to the address a redirect names.
|
|
161
|
+
"""
|
|
162
|
+
http = self._storage if storage else self._http
|
|
163
|
+
final = len(DELAYS) if retries else 0
|
|
164
|
+
headers = dict(kwargs.pop("headers", None) or {})
|
|
165
|
+
if auth and not storage and self.token:
|
|
166
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
167
|
+
sending: dict[str, Any] = {"follow_redirects": False} if raw else {}
|
|
168
|
+
last: httpx.Response | None = None
|
|
169
|
+
for attempt in range(final + 1):
|
|
170
|
+
request = http.build_request(method, path, headers=headers, **kwargs)
|
|
171
|
+
try:
|
|
172
|
+
response = http.send(request, **sending)
|
|
173
|
+
except NOT_SENT as exc:
|
|
174
|
+
self._log(request, None, type(exc).__name__)
|
|
175
|
+
if attempt == final:
|
|
176
|
+
raise CliError(
|
|
177
|
+
Exit.NETWORK,
|
|
178
|
+
f"Нет соединения с {self.base_url}.",
|
|
179
|
+
"Проверьте сеть, прокси (--proxy, HTTPS_PROXY) и адрес (--url).",
|
|
180
|
+
) from exc
|
|
181
|
+
self._wait(attempt, None)
|
|
182
|
+
continue
|
|
183
|
+
except httpx.TransportError as exc:
|
|
184
|
+
self._log(request, None, type(exc).__name__)
|
|
185
|
+
if once:
|
|
186
|
+
raise LostAnswer(str(exc)) from exc
|
|
187
|
+
if attempt == final:
|
|
188
|
+
raise CliError(Exit.NETWORK, "Соединение обрывается. Повторите позже.") from exc
|
|
189
|
+
self._wait(attempt, None)
|
|
190
|
+
continue
|
|
191
|
+
self._log(request, response)
|
|
192
|
+
last = response
|
|
193
|
+
if response.status_code < 400:
|
|
194
|
+
return response
|
|
195
|
+
if response.status_code >= 500 and error_of(response).code == "channel_unavailable":
|
|
196
|
+
break
|
|
197
|
+
if once and not raw and response.status_code >= 500:
|
|
198
|
+
# The hand-in may have been stored before the server or the gateway failed.
|
|
199
|
+
raise LostAnswer(f"{response.status_code}")
|
|
200
|
+
if response.status_code in RETRY_STATUS and attempt < final:
|
|
201
|
+
self._wait(attempt, response)
|
|
202
|
+
continue
|
|
203
|
+
break
|
|
204
|
+
assert last is not None
|
|
205
|
+
if raw:
|
|
206
|
+
return last
|
|
207
|
+
raise error_of(last)
|
|
208
|
+
|
|
209
|
+
def call(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
210
|
+
"""A JSON call to the API; platform errors become `CliError`."""
|
|
211
|
+
try:
|
|
212
|
+
response = self.send(method, path, **kwargs)
|
|
213
|
+
except ApiError as error:
|
|
214
|
+
raise from_api(error, base_url=self.base_url) from error
|
|
215
|
+
if not response.content:
|
|
216
|
+
return None
|
|
217
|
+
try:
|
|
218
|
+
return response.json()
|
|
219
|
+
except ValueError as exc:
|
|
220
|
+
if kwargs.get("once"):
|
|
221
|
+
# Something between us and the platform answered; the hand-in may still be stored.
|
|
222
|
+
raise LostAnswer("not json") from exc
|
|
223
|
+
raise CliError(
|
|
224
|
+
Exit.NETWORK,
|
|
225
|
+
f"Вместо ответа платформы пришла чужая страница ({self.base_url}).",
|
|
226
|
+
"Похоже, сеть требует входа (Wi-Fi с авторизацией) или прокси подменяет ответы. "
|
|
227
|
+
"Войдите в сеть в браузере, проверьте --proxy и --url и повторите.",
|
|
228
|
+
code="not_json",
|
|
229
|
+
) from exc
|
|
230
|
+
|
|
231
|
+
def get(self, path: str, **kwargs: Any) -> Any:
|
|
232
|
+
return self.call("GET", path, **kwargs)
|
|
233
|
+
|
|
234
|
+
def post(self, path: str, body: Any = None, **kwargs: Any) -> Any:
|
|
235
|
+
return self.call("POST", path, json=body if body is not None else {}, **kwargs)
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def storage(self) -> httpx.Client:
|
|
239
|
+
return self._storage
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""One module per group of commands; `main.py` registers them."""
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""`api`: one raw call to the platform's API with the CLI's token, in the spirit of `gh api`.
|
|
2
|
+
|
|
3
|
+
The token goes to one place only: `/api/v1/` of the profile's platform address. Another origin, a
|
|
4
|
+
path that leaves `/api/v1/`, a credential header and a redirect are refused or not followed before
|
|
5
|
+
anything reaches another host, and every byte the command prints has the token replaced
|
|
6
|
+
(`openspec/changes/cli-api/design.md`, D2, D3, D6, D10).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Annotated, Any
|
|
15
|
+
from urllib.parse import unquote, urlsplit
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
import typer
|
|
19
|
+
|
|
20
|
+
from .. import CLIENT_HEADER
|
|
21
|
+
from ..client import error_of
|
|
22
|
+
from ..errors import CliError, Exit, from_api
|
|
23
|
+
from ..output import clean
|
|
24
|
+
from ..session import JsonOpt, Session, execute
|
|
25
|
+
|
|
26
|
+
METHODS = ("GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE")
|
|
27
|
+
SAFE = frozenset({"GET", "HEAD", "OPTIONS"})
|
|
28
|
+
QUERY_METHODS = frozenset({"GET", "HEAD"})
|
|
29
|
+
# The token, a cookie, another virtual host, and the client header `submission-channels` reads.
|
|
30
|
+
REFUSED_HEADERS = frozenset({"authorization", "cookie", "host", CLIENT_HEADER.lower()})
|
|
31
|
+
API_ROOT = "/api/v1/"
|
|
32
|
+
HIDDEN = "<скрыт>"
|
|
33
|
+
INTEGER = re.compile(r"-?\d+")
|
|
34
|
+
PORTS = {"https": 443, "http": 80}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _usage(message: str, code: str, hint: str = "") -> CliError:
|
|
38
|
+
return CliError(Exit.USAGE, message, hint, code=code)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _origin(scheme: str, host: str | None, port: int | None) -> tuple[str, str, int | None]:
|
|
42
|
+
scheme = scheme.lower()
|
|
43
|
+
return scheme, (host or "").lower(), port or PORTS.get(scheme)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def api_path(site: str, path: str) -> str:
|
|
47
|
+
"""PATH as the address under the platform's `/api/v1/` (with its query), or a refusal."""
|
|
48
|
+
root = urlsplit(site)
|
|
49
|
+
prefix = root.path.rstrip("/") + API_ROOT
|
|
50
|
+
given = urlsplit(path)
|
|
51
|
+
# The parsed parts, not the text: `urlsplit` drops leading spaces and control characters, so
|
|
52
|
+
# " //host/..." has a host although the text does not start with "//".
|
|
53
|
+
if given.scheme or given.netloc:
|
|
54
|
+
if _origin(given.scheme, given.hostname, given.port) != _origin(
|
|
55
|
+
root.scheme, root.hostname, root.port
|
|
56
|
+
):
|
|
57
|
+
raise _usage(
|
|
58
|
+
f"Адрес {path} — не эта платформа ({site}): токен туда не уйдёт.",
|
|
59
|
+
"foreign_url",
|
|
60
|
+
"Пишите путь от /api/v1/, например: orangehack api accounts/tokens/current",
|
|
61
|
+
)
|
|
62
|
+
if not given.path.startswith(prefix):
|
|
63
|
+
raise _usage(f"Адрес {path} не в API платформы ({API_ROOT}).", "outside_api")
|
|
64
|
+
rest = given.path[len(prefix) :]
|
|
65
|
+
else:
|
|
66
|
+
rest = given.path.lstrip("/")
|
|
67
|
+
if rest == API_ROOT.strip("/") or rest.startswith(API_ROOT.lstrip("/")):
|
|
68
|
+
rest = rest[len(API_ROOT.lstrip("/")) :]
|
|
69
|
+
if any(segment in (".", "..") for segment in unquote(rest).split("/")):
|
|
70
|
+
raise _usage(f"Путь {path} выходит из {API_ROOT}: так нельзя.", "outside_api")
|
|
71
|
+
return API_ROOT + rest + (f"?{given.query}" if given.query else "")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _pair(item: str, flag: str) -> tuple[str, str]:
|
|
75
|
+
key, sep, value = item.partition("=")
|
|
76
|
+
if not sep or not key:
|
|
77
|
+
raise _usage(f"{flag} ждёт ключ=значение, а получил «{item}».", "bad_field")
|
|
78
|
+
return key, value
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _typed(value: str) -> Any:
|
|
82
|
+
"""`-F`, as `gh api -F` without `@file`: true, false, null and integers become JSON values."""
|
|
83
|
+
literals: dict[str, Any] = {"true": True, "false": False, "null": None}
|
|
84
|
+
if value in literals:
|
|
85
|
+
return literals[value]
|
|
86
|
+
if INTEGER.fullmatch(value):
|
|
87
|
+
return int(value)
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _headers(items: list[str]) -> dict[str, str]:
|
|
92
|
+
headers: dict[str, str] = {}
|
|
93
|
+
for item in items:
|
|
94
|
+
name, sep, value = item.partition(":")
|
|
95
|
+
name = name.strip()
|
|
96
|
+
if not sep or not name:
|
|
97
|
+
raise _usage(f"-H ждёт «Имя: значение», а получил «{item}».", "bad_header")
|
|
98
|
+
if name.lower() in REFUSED_HEADERS:
|
|
99
|
+
raise _usage(
|
|
100
|
+
f"Заголовок {name} задавать нельзя: его ставит сама команда.",
|
|
101
|
+
"header_not_allowed",
|
|
102
|
+
)
|
|
103
|
+
headers[name] = value.strip()
|
|
104
|
+
return headers
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _read_input(source: str) -> bytes:
|
|
108
|
+
if source == "-":
|
|
109
|
+
return typer.get_binary_stream("stdin").read()
|
|
110
|
+
try:
|
|
111
|
+
return Path(source).read_bytes()
|
|
112
|
+
except OSError as exc:
|
|
113
|
+
raise _usage(f"Не удалось прочитать {source}.", "no_input") from exc
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class Scrub:
|
|
117
|
+
"""Replaces the token in everything the command prints."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, token: str) -> None:
|
|
120
|
+
self.token = token
|
|
121
|
+
|
|
122
|
+
def text(self, value: str) -> str:
|
|
123
|
+
return value.replace(self.token, HIDDEN) if self.token else value
|
|
124
|
+
|
|
125
|
+
def bytes(self, value: bytes) -> bytes:
|
|
126
|
+
return value.replace(self.token.encode(), HIDDEN.encode()) if self.token else value
|
|
127
|
+
|
|
128
|
+
def error(self, error: CliError) -> CliError:
|
|
129
|
+
"""Every text of an error the command prints; `extra` is scrubbed by its builder."""
|
|
130
|
+
error.message, error.hint = self.text(error.message), self.text(error.hint)
|
|
131
|
+
error.code, error.detail = self.text(error.code), self.text(error.detail)
|
|
132
|
+
return error
|
|
133
|
+
|
|
134
|
+
def value(self, value: Any) -> Any:
|
|
135
|
+
"""A parsed JSON value: a token the answer wrote as `\\uXXXX` escapes is plain text here."""
|
|
136
|
+
if not self.token:
|
|
137
|
+
return value
|
|
138
|
+
return json.loads(self.text(json.dumps(value, ensure_ascii=False)))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _is_json(response: httpx.Response) -> bool:
|
|
142
|
+
return "json" in response.headers.get("content-type", "").lower()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _parsed(content: bytes, is_json: bool) -> Any:
|
|
146
|
+
"""The body for the `--json` document: JSON as JSON, anything else as text, empty as null."""
|
|
147
|
+
if not content:
|
|
148
|
+
return None
|
|
149
|
+
if is_json:
|
|
150
|
+
try:
|
|
151
|
+
return json.loads(content)
|
|
152
|
+
except ValueError:
|
|
153
|
+
pass
|
|
154
|
+
return content.decode("utf-8", errors="replace")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# A JSON string escape of a character that needs none (`\u0420`), or an escaped backslash, which is
|
|
158
|
+
# skipped so that `\\u0420` (a backslash and the text u0420) is left as it is.
|
|
159
|
+
_ESCAPE = re.compile(rb"\\\\|\\u([0-9a-fA-F]{4})(?:\\u([dD][c-fC-F][0-9a-fA-F]{2}))?")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _letter(found: re.Match[bytes]) -> bytes:
|
|
163
|
+
if found.group(1) is None:
|
|
164
|
+
return found.group(0)
|
|
165
|
+
code = int(found.group(1), 16)
|
|
166
|
+
tail = b""
|
|
167
|
+
if found.group(2) is not None and not 0xD800 <= code <= 0xDBFF:
|
|
168
|
+
tail = b"\\u" + found.group(2) # a lone low surrogate after a plain letter stays escaped
|
|
169
|
+
elif found.group(2) is not None:
|
|
170
|
+
code = 0x10000 + ((code - 0xD800) << 10) + (int(found.group(2), 16) - 0xDC00)
|
|
171
|
+
# What a JSON string must keep escaped, and a lone surrogate, which has no UTF-8 form.
|
|
172
|
+
if code < 0x20 or code in (0x22, 0x5C) or 0xD800 <= code <= 0xDFFF:
|
|
173
|
+
return found.group(0)
|
|
174
|
+
return chr(code).encode() + tail
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def readable(content: bytes) -> bytes:
|
|
178
|
+
"""A JSON body with its `\\uXXXX` escapes written as the characters (Django escapes every
|
|
179
|
+
Cyrillic letter), every other byte as received."""
|
|
180
|
+
return _ESCAPE.sub(_letter, content)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def render(content: bytes, is_json: bool, tty: bool) -> bytes:
|
|
184
|
+
"""The body for stdout: as received in a pipe (a JSON body with its Cyrillic written as letters);
|
|
185
|
+
indented JSON or cleaned text in a terminal."""
|
|
186
|
+
if not content:
|
|
187
|
+
return content
|
|
188
|
+
if not tty:
|
|
189
|
+
return readable(content) if is_json else content
|
|
190
|
+
if is_json:
|
|
191
|
+
try:
|
|
192
|
+
pretty = json.dumps(json.loads(content), ensure_ascii=False, indent=2)
|
|
193
|
+
encoded = (pretty + "\n").encode()
|
|
194
|
+
except (ValueError, UnicodeEncodeError):
|
|
195
|
+
pass
|
|
196
|
+
else:
|
|
197
|
+
return encoded
|
|
198
|
+
text = clean(content.decode("utf-8", errors="replace"))
|
|
199
|
+
return (text if text.endswith("\n") else text + "\n").encode()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def api(
|
|
203
|
+
ctx: typer.Context,
|
|
204
|
+
target: Annotated[
|
|
205
|
+
list[str],
|
|
206
|
+
typer.Argument(
|
|
207
|
+
metavar="[METHOD] PATH",
|
|
208
|
+
help="Метод (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) и путь от /api/v1/.",
|
|
209
|
+
show_default=False,
|
|
210
|
+
),
|
|
211
|
+
],
|
|
212
|
+
raw_fields: Annotated[
|
|
213
|
+
list[str] | None,
|
|
214
|
+
typer.Option(
|
|
215
|
+
"-f",
|
|
216
|
+
"--raw-field",
|
|
217
|
+
metavar="KEY=VALUE",
|
|
218
|
+
help="Поле-строка ключ=значение (у GET — в адрес).",
|
|
219
|
+
),
|
|
220
|
+
] = None,
|
|
221
|
+
fields: Annotated[
|
|
222
|
+
list[str] | None,
|
|
223
|
+
typer.Option(
|
|
224
|
+
"-F",
|
|
225
|
+
"--field",
|
|
226
|
+
metavar="KEY=VALUE",
|
|
227
|
+
help="Поле ключ=значение: true, false, null и целые — JSON.",
|
|
228
|
+
),
|
|
229
|
+
] = None,
|
|
230
|
+
input_: Annotated[
|
|
231
|
+
str | None,
|
|
232
|
+
typer.Option("--input", metavar="FILE", help="Тело запроса из файла (- — из stdin)."),
|
|
233
|
+
] = None,
|
|
234
|
+
header: Annotated[
|
|
235
|
+
list[str] | None,
|
|
236
|
+
typer.Option("-H", "--header", metavar="NAME:VALUE", help="Заголовок «Имя: значение»."),
|
|
237
|
+
] = None,
|
|
238
|
+
include: Annotated[
|
|
239
|
+
bool, typer.Option("-i", "--include", help="Показать код и заголовки ответа.")
|
|
240
|
+
] = False,
|
|
241
|
+
json_: JsonOpt = False,
|
|
242
|
+
) -> None:
|
|
243
|
+
"""Запрос к API платформы с вашим токеном, как gh api.
|
|
244
|
+
|
|
245
|
+
Путь пишется от /api/v1/: orangehack api accounts/tokens/current. Метод по умолчанию GET,
|
|
246
|
+
с полями или телом — POST. Токен уходит только на эту платформу; по перенаправлениям
|
|
247
|
+
команда не ходит. Ответ 400 и выше — ненулевой код выхода по таблице orangehack --help.
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
def body(s: Session) -> None:
|
|
251
|
+
scrub = Scrub(s.profile.token)
|
|
252
|
+
try:
|
|
253
|
+
call(s, scrub)
|
|
254
|
+
except CliError as error:
|
|
255
|
+
# A refusal may quote PATH, a field or a header, where a person may have put the token.
|
|
256
|
+
raise scrub.error(error) from None
|
|
257
|
+
|
|
258
|
+
def call(s: Session, scrub: Scrub) -> None:
|
|
259
|
+
if len(target) > 2:
|
|
260
|
+
raise _usage("Нужны [МЕТОД] и ПУТЬ, лишние аргументы.", "bad_arguments")
|
|
261
|
+
method = target[0].upper() if len(target) == 2 else ""
|
|
262
|
+
if method and method not in METHODS:
|
|
263
|
+
raise _usage(f"Метод {target[0]} не поддерживается.", "bad_method", ", ".join(METHODS))
|
|
264
|
+
path = api_path(s.profile.url, target[-1])
|
|
265
|
+
pairs = [_pair(item, "-f") for item in raw_fields or []]
|
|
266
|
+
pairs += [(k, _typed(v)) for k, v in (_pair(item, "-F") for item in fields or [])]
|
|
267
|
+
if pairs and input_ is not None:
|
|
268
|
+
raise _usage("Поля (-f, -F) и --input вместе не отправить.", "body_twice")
|
|
269
|
+
headers = _headers(header or [])
|
|
270
|
+
method = method or ("POST" if pairs or input_ is not None else "GET")
|
|
271
|
+
request: dict[str, Any] = {}
|
|
272
|
+
content: bytes | None = None
|
|
273
|
+
if pairs and method in QUERY_METHODS:
|
|
274
|
+
request["params"] = pairs
|
|
275
|
+
elif pairs:
|
|
276
|
+
content = json.dumps(dict(pairs), ensure_ascii=False).encode()
|
|
277
|
+
elif input_ is not None:
|
|
278
|
+
content = _read_input(input_)
|
|
279
|
+
if content is not None:
|
|
280
|
+
request["content"] = content
|
|
281
|
+
if not any(name.lower() == "content-type" for name in headers):
|
|
282
|
+
headers["Content-Type"] = "application/json"
|
|
283
|
+
|
|
284
|
+
client = s.signed_in()
|
|
285
|
+
response = client.send(
|
|
286
|
+
method,
|
|
287
|
+
path,
|
|
288
|
+
raw=True,
|
|
289
|
+
retries=method in SAFE,
|
|
290
|
+
once=method not in SAFE,
|
|
291
|
+
headers=headers,
|
|
292
|
+
**request,
|
|
293
|
+
)
|
|
294
|
+
_show(s, response, include, scrub)
|
|
295
|
+
|
|
296
|
+
execute(ctx, json_, body)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _tty(out: Any) -> bool:
|
|
300
|
+
return bool(out.isatty())
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _show(s: Session, response: httpx.Response, include: bool, scrub: Scrub) -> None:
|
|
304
|
+
status = response.status_code
|
|
305
|
+
content = scrub.bytes(response.content)
|
|
306
|
+
headers = [(name, scrub.text(value)) for name, value in response.headers.multi_items()]
|
|
307
|
+
location = scrub.text(response.headers.get("location", ""))
|
|
308
|
+
is_json = _is_json(response)
|
|
309
|
+
if s.output.json_mode:
|
|
310
|
+
body = scrub.value(_parsed(content, is_json))
|
|
311
|
+
document: dict[str, Any] = {"status": status, "body": body}
|
|
312
|
+
if include:
|
|
313
|
+
# Pairs, not an object: a header may repeat (`Set-Cookie`).
|
|
314
|
+
document["headers"] = [[name, value] for name, value in headers]
|
|
315
|
+
if location:
|
|
316
|
+
document["location"] = location
|
|
317
|
+
if status < 400:
|
|
318
|
+
print(scrub.text(json.dumps({"ok": True, **document}, ensure_ascii=False)))
|
|
319
|
+
return
|
|
320
|
+
raise _failure(response, content, scrub, document)
|
|
321
|
+
out = s.output.out
|
|
322
|
+
tty = _tty(out)
|
|
323
|
+
stream = typer.get_binary_stream("stdout")
|
|
324
|
+
if include:
|
|
325
|
+
lines = [f"{response.http_version} {status} {response.reason_phrase}"]
|
|
326
|
+
lines += [f"{name}: {value}" for name, value in headers]
|
|
327
|
+
head = "\n".join(lines) + "\n\n"
|
|
328
|
+
stream.write((clean(head) if tty else head).encode())
|
|
329
|
+
# Scrubbed again after formatting: indenting decodes a token the answer JSON-escaped.
|
|
330
|
+
stream.write(scrub.bytes(render(content, is_json, tty)))
|
|
331
|
+
stream.flush()
|
|
332
|
+
if 300 <= status < 400 and location:
|
|
333
|
+
s.output.note(f"Платформа перенаправляет: {location}")
|
|
334
|
+
if status >= 400:
|
|
335
|
+
raise _failure(response, content, scrub, {})
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _failure(
|
|
339
|
+
response: httpx.Response, content: bytes, scrub: Scrub, extra: dict[str, Any]
|
|
340
|
+
) -> CliError:
|
|
341
|
+
# The error is read from the scrubbed body, so its code and detail cannot carry the token.
|
|
342
|
+
scrubbed = httpx.Response(response.status_code, content=content)
|
|
343
|
+
platform = error_of(scrubbed)
|
|
344
|
+
error = from_api(platform)
|
|
345
|
+
error.message = f"HTTP {platform.status} {platform.code}. {error.message}"
|
|
346
|
+
error.extra = extra
|
|
347
|
+
return scrub.error(error)
|