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/errors.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Stable exit codes and the mapping from the platform's `{code, detail}` answers to them.
|
|
2
|
+
|
|
3
|
+
The exit codes are part of the public contract: they do not change meaning within a major version
|
|
4
|
+
(`openspec/specs/cli`). Messages are Russian and written for people; `detail` from the platform is
|
|
5
|
+
kept beside them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from enum import IntEnum
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Exit(IntEnum):
|
|
16
|
+
OK = 0
|
|
17
|
+
REFUSED = 1 # the platform stored the attempt as refused, or the run failed
|
|
18
|
+
USAGE = 2 # a missing argument, an ambiguous target
|
|
19
|
+
SIGNED_OUT = 3 # not signed in, or the token is dead
|
|
20
|
+
FORBIDDEN = 4 # not allowed
|
|
21
|
+
CONSENT = 5 # documents to accept first
|
|
22
|
+
LIMIT = 6 # a limit or a window
|
|
23
|
+
NETWORK = 7 # network or server after the retries
|
|
24
|
+
TOO_OLD = 8 # the CLI is older than the platform's minimum
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class CliError(Exception):
|
|
29
|
+
exit: Exit
|
|
30
|
+
message: str
|
|
31
|
+
hint: str = ""
|
|
32
|
+
code: str = ""
|
|
33
|
+
detail: str = ""
|
|
34
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
def __str__(self) -> str:
|
|
37
|
+
return self.message
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class ApiError(Exception):
|
|
42
|
+
"""A non-2xx answer of the platform, before it is turned into a `CliError`."""
|
|
43
|
+
|
|
44
|
+
status: int
|
|
45
|
+
code: str
|
|
46
|
+
detail: str
|
|
47
|
+
body: dict[str, Any] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
def __str__(self) -> str:
|
|
50
|
+
return f"{self.status} {self.code}: {self.detail}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class LostAnswer(Exception):
|
|
54
|
+
"""The request was sent and the connection broke before the answer came."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def from_api(error: ApiError, *, base_url: str = "") -> CliError:
|
|
58
|
+
"""One place that decides what a platform answer means for the person and the exit code."""
|
|
59
|
+
code, status, detail = error.code, error.status, error.detail
|
|
60
|
+
|
|
61
|
+
def fail(exit_: Exit, message: str, hint: str = "") -> CliError:
|
|
62
|
+
return CliError(exit_, message, hint, code=code, detail=detail)
|
|
63
|
+
|
|
64
|
+
if code == "tokens_disabled":
|
|
65
|
+
return fail(Exit.SIGNED_OUT, "Доступ по токенам на платформе сейчас выключен.")
|
|
66
|
+
if status == 401 or code == "token_invalid":
|
|
67
|
+
return fail(
|
|
68
|
+
Exit.SIGNED_OUT,
|
|
69
|
+
"Вы не вошли, или токен больше не действует.",
|
|
70
|
+
"Войдите заново: orangehack login",
|
|
71
|
+
)
|
|
72
|
+
if code == "token_scope":
|
|
73
|
+
return fail(
|
|
74
|
+
Exit.FORBIDDEN,
|
|
75
|
+
"У токена нет права на это действие.",
|
|
76
|
+
"Войдите с правом сдавать: orangehack login --scope read,submit",
|
|
77
|
+
)
|
|
78
|
+
if code == "token_scope_unavailable":
|
|
79
|
+
return fail(
|
|
80
|
+
Exit.FORBIDDEN,
|
|
81
|
+
"Право сдавать из терминала на платформе пока не включено.",
|
|
82
|
+
"Войдите только на чтение: orangehack login --scope read",
|
|
83
|
+
)
|
|
84
|
+
if code == "token_not_allowed":
|
|
85
|
+
return fail(Exit.FORBIDDEN, "Это действие недоступно по токену: сделайте его на сайте.")
|
|
86
|
+
if code == "consent_required":
|
|
87
|
+
where = f"{base_url.rstrip('/')}/consents" if base_url else "раздел «Согласия» на сайте"
|
|
88
|
+
return fail(
|
|
89
|
+
Exit.CONSENT,
|
|
90
|
+
"Сначала примите обновлённые документы платформы.",
|
|
91
|
+
f"Откройте {where} и вернитесь в терминал.",
|
|
92
|
+
)
|
|
93
|
+
if code in ("rate_limited",) or status == 429:
|
|
94
|
+
return fail(Exit.LIMIT, "Слишком много запросов. Подождите минуту и повторите.")
|
|
95
|
+
if code == "channel_unavailable" or status >= 500:
|
|
96
|
+
return fail(
|
|
97
|
+
Exit.NETWORK,
|
|
98
|
+
"Платформа сейчас не отвечает как надо. Повторите позже.",
|
|
99
|
+
)
|
|
100
|
+
if code == "channel_off":
|
|
101
|
+
return fail(Exit.REFUSED, detail or "Это соревнование не принимает сдачу из терминала.")
|
|
102
|
+
if status == 403:
|
|
103
|
+
return fail(Exit.FORBIDDEN, detail or "Нет доступа.")
|
|
104
|
+
if status == 404:
|
|
105
|
+
return fail(Exit.FORBIDDEN, "Не найдено, или у вас нет к этому доступа.")
|
|
106
|
+
if status == 409:
|
|
107
|
+
return fail(Exit.LIMIT, detail or "Сейчас это сделать нельзя.")
|
|
108
|
+
# 400 and 422: the platform refused the input; its sentence says why.
|
|
109
|
+
return fail(Exit.USAGE, detail or "Платформа не приняла запрос.")
|
orangehack/main.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""The `orangehack` command."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .commands import api, attempts, auth, competitions, download, leaderboard, submit
|
|
11
|
+
from .output import force_utf8
|
|
12
|
+
from .session import Options
|
|
13
|
+
|
|
14
|
+
EXIT_CODES = """Коды выхода: 0 готово · 1 платформа отклонила попытку или оценка не удалась ·
|
|
15
|
+
2 неверный вызов · 3 не выполнен вход · 4 нет прав · 5 нужно принять документы ·
|
|
16
|
+
6 лимит или окно · 7 сеть или сервер · 8 версия CLI устарела."""
|
|
17
|
+
|
|
18
|
+
app = typer.Typer(
|
|
19
|
+
name="orangehack",
|
|
20
|
+
help=(
|
|
21
|
+
"Сдача решений на платформу OrangeHack из терминала.\n\n"
|
|
22
|
+
"Начните с orangehack login. Документация: https://app.orangehack.ru/docs/cli\n\n"
|
|
23
|
+
+ EXIT_CODES
|
|
24
|
+
),
|
|
25
|
+
no_args_is_help=True,
|
|
26
|
+
add_completion=True,
|
|
27
|
+
pretty_exceptions_enable=False,
|
|
28
|
+
rich_markup_mode=None,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _version(value: bool) -> None:
|
|
33
|
+
if value:
|
|
34
|
+
typer.echo(f"orangehack {__version__}")
|
|
35
|
+
raise typer.Exit()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@app.callback()
|
|
39
|
+
def main(
|
|
40
|
+
ctx: typer.Context,
|
|
41
|
+
profile: Annotated[
|
|
42
|
+
str | None,
|
|
43
|
+
typer.Option("--profile", envvar="ORANGEHACK_PROFILE", help="Профиль из config.toml."),
|
|
44
|
+
] = None,
|
|
45
|
+
url: Annotated[
|
|
46
|
+
str | None,
|
|
47
|
+
typer.Option("--url", help="Адрес платформы (или ORANGEHACK_URL)."),
|
|
48
|
+
] = None,
|
|
49
|
+
proxy: Annotated[
|
|
50
|
+
str | None, typer.Option("--proxy", help="Прокси, например http://proxy:3128.")
|
|
51
|
+
] = None,
|
|
52
|
+
ca_bundle: Annotated[
|
|
53
|
+
str | None,
|
|
54
|
+
typer.Option(
|
|
55
|
+
"--ca-bundle", envvar="ORANGEHACK_CA_BUNDLE", help="Свой файл корневых сертификатов."
|
|
56
|
+
),
|
|
57
|
+
] = None,
|
|
58
|
+
verbose: Annotated[
|
|
59
|
+
bool, typer.Option("--verbose", "-v", help="Показать запросы (без токена).")
|
|
60
|
+
] = False,
|
|
61
|
+
json_: Annotated[
|
|
62
|
+
bool, typer.Option("--json", help="Один JSON-документ в stdout для любой команды.")
|
|
63
|
+
] = False,
|
|
64
|
+
version: Annotated[
|
|
65
|
+
bool,
|
|
66
|
+
typer.Option("--version", callback=_version, is_eager=True, help="Показать версию."),
|
|
67
|
+
] = False,
|
|
68
|
+
) -> None:
|
|
69
|
+
if isinstance(ctx.obj, Options): # tests pass their own transport and clock
|
|
70
|
+
options = ctx.obj
|
|
71
|
+
options.profile, options.url, options.proxy = profile, url, proxy
|
|
72
|
+
options.ca_bundle, options.verbose = ca_bundle, verbose
|
|
73
|
+
options.json = options.json or json_
|
|
74
|
+
else:
|
|
75
|
+
ctx.obj = Options(profile, url, proxy, ca_bundle, verbose, json_)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
app.command()(auth.login)
|
|
79
|
+
app.command()(auth.logout)
|
|
80
|
+
app.command()(auth.whoami)
|
|
81
|
+
app.command()(competitions.competitions)
|
|
82
|
+
app.command()(competitions.cases)
|
|
83
|
+
app.command()(competitions.deliverables)
|
|
84
|
+
app.command()(submit.submit)
|
|
85
|
+
app.command()(attempts.attempts)
|
|
86
|
+
app.command()(attempts.status)
|
|
87
|
+
app.command()(leaderboard.leaderboard)
|
|
88
|
+
app.command()(download.download)
|
|
89
|
+
app.command()(api.api)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run() -> None:
|
|
93
|
+
force_utf8()
|
|
94
|
+
app()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
if __name__ == "__main__":
|
|
98
|
+
run()
|
orangehack/output.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Tables for people, one JSON document for scripts.
|
|
2
|
+
|
|
3
|
+
Under `--json` stdout carries exactly one JSON object (`{"ok": true, ...}` or
|
|
4
|
+
`{"ok": false, "code", "detail", "exit", ...}`); progress and notices go to stderr, and progress is
|
|
5
|
+
silent when stderr is not a terminal.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
import unicodedata
|
|
15
|
+
from collections.abc import Callable, Sequence
|
|
16
|
+
from typing import Any, TextIO
|
|
17
|
+
|
|
18
|
+
from .errors import CliError
|
|
19
|
+
|
|
20
|
+
# Control characters other than a newline and a tab: a server string (a material's title, an
|
|
21
|
+
# organiser's sentence) must not move the cursor, recolour or retitle the person's terminal.
|
|
22
|
+
_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def clean(text: str) -> str:
|
|
26
|
+
return _CONTROL.sub("", text)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _width(text: str) -> int:
|
|
30
|
+
return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in text)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def table(headers: Sequence[str], rows: Sequence[Sequence[Any]]) -> str:
|
|
34
|
+
cells = [[("" if v is None else clean(str(v))) for v in row] for row in rows]
|
|
35
|
+
widths = [_width(h) for h in headers]
|
|
36
|
+
for row in cells:
|
|
37
|
+
for i, value in enumerate(row):
|
|
38
|
+
widths[i] = max(widths[i], _width(value))
|
|
39
|
+
|
|
40
|
+
def line(values: Sequence[str]) -> str:
|
|
41
|
+
return " ".join(v + " " * (widths[i] - _width(v)) for i, v in enumerate(values)).rstrip()
|
|
42
|
+
|
|
43
|
+
return "\n".join([line(headers), *(line(row) for row in cells)])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Output:
|
|
47
|
+
def __init__(self, json_mode: bool = False, *, out: TextIO | None = None) -> None:
|
|
48
|
+
self.json_mode = json_mode
|
|
49
|
+
self.out = out or sys.stdout
|
|
50
|
+
self.err = sys.stderr
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def interactive(self) -> bool:
|
|
54
|
+
return self.err.isatty()
|
|
55
|
+
|
|
56
|
+
def say(self, text: str = "") -> None:
|
|
57
|
+
"""A line for people: stdout normally, stderr under --json."""
|
|
58
|
+
print(clean(text), file=self.err if self.json_mode else self.out)
|
|
59
|
+
|
|
60
|
+
def note(self, text: str) -> None:
|
|
61
|
+
"""A notice that is never part of the result."""
|
|
62
|
+
print(clean(text), file=self.err)
|
|
63
|
+
|
|
64
|
+
def progress(self, text: str) -> None:
|
|
65
|
+
if self.interactive:
|
|
66
|
+
print(f"\r{clean(text)}\033[K", end="", file=self.err, flush=True)
|
|
67
|
+
|
|
68
|
+
def progress_done(self) -> None:
|
|
69
|
+
if self.interactive:
|
|
70
|
+
print(file=self.err)
|
|
71
|
+
|
|
72
|
+
def result(self, data: dict[str, Any], human: Callable[[], None] | None = None) -> None:
|
|
73
|
+
if self.json_mode:
|
|
74
|
+
print(json.dumps({"ok": True, **data}, ensure_ascii=False), file=self.out)
|
|
75
|
+
elif human is not None:
|
|
76
|
+
human()
|
|
77
|
+
|
|
78
|
+
def error(self, error: CliError) -> None:
|
|
79
|
+
if self.json_mode:
|
|
80
|
+
body: dict[str, Any] = {
|
|
81
|
+
"ok": False,
|
|
82
|
+
"code": error.code or error.exit.name.lower(),
|
|
83
|
+
"detail": error.detail or error.message,
|
|
84
|
+
"message": error.message,
|
|
85
|
+
"exit": int(error.exit),
|
|
86
|
+
}
|
|
87
|
+
if error.hint:
|
|
88
|
+
body["hint"] = error.hint
|
|
89
|
+
body.update(error.extra)
|
|
90
|
+
print(json.dumps(body, ensure_ascii=False), file=self.out)
|
|
91
|
+
return
|
|
92
|
+
print(f"Ошибка: {clean(error.message)}", file=self.err)
|
|
93
|
+
if error.detail and error.detail not in error.message:
|
|
94
|
+
print(f"Платформа: {clean(error.detail)}", file=self.err)
|
|
95
|
+
if error.hint:
|
|
96
|
+
print(clean(error.hint), file=self.err)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def force_utf8() -> None:
|
|
100
|
+
"""Windows consoles default to a code page that cannot print Russian."""
|
|
101
|
+
for stream in (sys.stdout, sys.stderr):
|
|
102
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
103
|
+
if reconfigure is not None:
|
|
104
|
+
with contextlib.suppress(ValueError, OSError):
|
|
105
|
+
reconfigure(encoding="utf-8", errors="replace")
|
orangehack/resolve.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Names people type -> ids: a competition by id or `org/slug`, a case or deliverable by key or
|
|
2
|
+
the start of its title. An ambiguous name lists the candidates and exits 2."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .client import Client
|
|
11
|
+
from .errors import CliError, Exit
|
|
12
|
+
|
|
13
|
+
UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Competition:
|
|
18
|
+
id: str
|
|
19
|
+
org: str
|
|
20
|
+
slug: str
|
|
21
|
+
title: str
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def address(self) -> str:
|
|
25
|
+
return f"{self.org}/{self.slug}"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Deliverable:
|
|
30
|
+
id: str
|
|
31
|
+
key: str
|
|
32
|
+
title: str
|
|
33
|
+
type: str
|
|
34
|
+
group_id: str
|
|
35
|
+
group_kind: str
|
|
36
|
+
group_title: str
|
|
37
|
+
# `attempts`: every version is checked by a program and scored; `replace`: people judge it.
|
|
38
|
+
mode: str = "replace"
|
|
39
|
+
window: dict[str, Any] = field(default_factory=dict)
|
|
40
|
+
blocked: dict[str, Any] | None = None
|
|
41
|
+
card: dict[str, Any] = field(default_factory=dict)
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def open(self) -> bool:
|
|
45
|
+
return self.window.get("state") == "open" and not self.blocked
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def scored(self) -> bool:
|
|
49
|
+
return self.mode == "attempts"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _ref(item: dict[str, Any]) -> Competition:
|
|
53
|
+
return Competition(
|
|
54
|
+
id=str(item["id"]),
|
|
55
|
+
org=str(item["organization"]["slug"]),
|
|
56
|
+
slug=str(item["slug"]),
|
|
57
|
+
title=str(item["title"]),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _address(text: str) -> str:
|
|
62
|
+
"""`https://app.orangehack.ru/events/org/slug/...`, `/events/org/slug`, `org/slug` -> `org/slug`."""
|
|
63
|
+
text = text.strip().rstrip("/")
|
|
64
|
+
text = re.sub(r"^https?://[^/]+", "", text)
|
|
65
|
+
text = re.sub(r"^/?events/", "", text).lstrip("/")
|
|
66
|
+
return "/".join(text.split("/")[:2])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def competition(client: Client, name: str) -> Competition:
|
|
70
|
+
mine = client.get("/api/v1/competitions/catalog/mine", params={"group": "participation"}) or []
|
|
71
|
+
refs = [_ref(item["competition"]) for item in mine]
|
|
72
|
+
if UUID.match(name.strip()):
|
|
73
|
+
for ref in refs:
|
|
74
|
+
if ref.id == name.strip():
|
|
75
|
+
return ref
|
|
76
|
+
address = _address(name)
|
|
77
|
+
for ref in refs:
|
|
78
|
+
if ref.address == address:
|
|
79
|
+
return ref
|
|
80
|
+
# Not one of mine: the catalog knows every public competition.
|
|
81
|
+
slug = address.split("/")[-1]
|
|
82
|
+
found = client.get("/api/v1/competitions/catalog", params={"q": slug, "limit": 50}) or {}
|
|
83
|
+
for item in found.get("items", []):
|
|
84
|
+
ref = _ref(item)
|
|
85
|
+
if ref.address == address or ref.id == name.strip():
|
|
86
|
+
return ref
|
|
87
|
+
raise CliError(
|
|
88
|
+
Exit.USAGE,
|
|
89
|
+
f"Соревнование «{name}» не найдено.",
|
|
90
|
+
"Назовите его адресом с сайта (организация/соревнование) — список: orangehack competitions",
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def deliverables(overview: dict[str, Any]) -> list[Deliverable]:
|
|
95
|
+
result = []
|
|
96
|
+
for group in overview.get("groups", []):
|
|
97
|
+
for card in group.get("items", []):
|
|
98
|
+
result.append(
|
|
99
|
+
Deliverable(
|
|
100
|
+
id=str(card["id"]),
|
|
101
|
+
key=str(card.get("key", "")),
|
|
102
|
+
title=str(card.get("title", "")),
|
|
103
|
+
type=str(card.get("type", "")),
|
|
104
|
+
group_id=str(group.get("id", "")),
|
|
105
|
+
group_kind=str(group.get("kind", "")),
|
|
106
|
+
group_title=str(group.get("title", "")),
|
|
107
|
+
mode=str(card.get("mode", "replace")),
|
|
108
|
+
window=dict(card.get("window") or {}),
|
|
109
|
+
blocked=card.get("blocked"),
|
|
110
|
+
card=card,
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _matches(name: str, *values: str) -> bool:
|
|
117
|
+
needle = name.casefold().strip()
|
|
118
|
+
return any(v and (v.casefold() == needle or v.casefold().startswith(needle)) for v in values)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _exact(name: str, *values: str) -> bool:
|
|
122
|
+
needle = name.casefold().strip()
|
|
123
|
+
return any(v and v.casefold() == needle for v in values)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def ambiguous(what: str, rows: list[Deliverable]) -> CliError:
|
|
127
|
+
listed = "\n".join(f" {d.key or d.id} {d.title} ({d.group_title})" for d in rows)
|
|
128
|
+
return CliError(
|
|
129
|
+
Exit.USAGE,
|
|
130
|
+
f"Подходит несколько {what}:\n{listed}",
|
|
131
|
+
"Уточните: --deliverable <ключ> или --case <кейс>",
|
|
132
|
+
code="ambiguous",
|
|
133
|
+
extra={"candidates": [{"key": d.key, "id": d.id, "title": d.title} for d in rows]},
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def narrow(
|
|
138
|
+
items: list[Deliverable],
|
|
139
|
+
*,
|
|
140
|
+
case: str | None = None,
|
|
141
|
+
deliverable: str | None = None,
|
|
142
|
+
case_keys: dict[str, str] | None = None,
|
|
143
|
+
) -> list[Deliverable]:
|
|
144
|
+
"""Filter by `--case` (the case's key or title) and `--deliverable` (key, id or title)."""
|
|
145
|
+
if case:
|
|
146
|
+
keys = case_keys or {}
|
|
147
|
+
exact = [d for d in items if _exact(case, d.group_title, keys.get(d.group_id, ""))]
|
|
148
|
+
items = exact or [
|
|
149
|
+
d for d in items if _matches(case, d.group_title, keys.get(d.group_id, ""))
|
|
150
|
+
]
|
|
151
|
+
if not items:
|
|
152
|
+
raise CliError(
|
|
153
|
+
Exit.USAGE, f"Кейс «{case}» не найден.", "Список: orangehack cases <соревнование>"
|
|
154
|
+
)
|
|
155
|
+
if deliverable:
|
|
156
|
+
exact = [d for d in items if _exact(deliverable, d.key, d.id, d.title)]
|
|
157
|
+
items = exact or [d for d in items if _matches(deliverable, d.key, d.title)]
|
|
158
|
+
if not items:
|
|
159
|
+
raise CliError(
|
|
160
|
+
Exit.USAGE,
|
|
161
|
+
f"Сдача «{deliverable}» не найдена.",
|
|
162
|
+
"Список: orangehack deliverables <соревнование>",
|
|
163
|
+
)
|
|
164
|
+
return items
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def one(items: list[Deliverable], what: str = "сдач") -> Deliverable:
|
|
168
|
+
if len(items) == 1:
|
|
169
|
+
return items[0]
|
|
170
|
+
if not items:
|
|
171
|
+
raise CliError(Exit.USAGE, "Ничего не найдено.")
|
|
172
|
+
raise ambiguous(what, items)
|
orangehack/session.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""What every command shares: the profile, the client, the output, and one place for errors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import traceback
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Annotated, Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
import typer
|
|
13
|
+
|
|
14
|
+
from . import config, version_check
|
|
15
|
+
from .client import Client
|
|
16
|
+
from .errors import CliError, Exit, LostAnswer
|
|
17
|
+
from .output import Output
|
|
18
|
+
|
|
19
|
+
JsonOpt = Annotated[
|
|
20
|
+
bool, typer.Option("--json", help="Один JSON-документ в stdout; прогресс — в stderr.")
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Options:
|
|
26
|
+
"""The global flags, given before the command (`orangehack --profile stage submit ...`)."""
|
|
27
|
+
|
|
28
|
+
profile: str | None = None
|
|
29
|
+
url: str | None = None
|
|
30
|
+
proxy: str | None = None
|
|
31
|
+
ca_bundle: str | None = None
|
|
32
|
+
verbose: bool = False
|
|
33
|
+
json: bool = False
|
|
34
|
+
# Tests replace the network and the clock.
|
|
35
|
+
transport: httpx.BaseTransport | None = None
|
|
36
|
+
sleep: Callable[[float], None] | None = None
|
|
37
|
+
open_browser: Callable[[str], Any] | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Session:
|
|
42
|
+
options: Options
|
|
43
|
+
output: Output
|
|
44
|
+
profile: config.Profile
|
|
45
|
+
_client: Client | None = field(default=None, repr=False)
|
|
46
|
+
_checked: bool = False
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def client(self) -> Client:
|
|
50
|
+
if self._client is None:
|
|
51
|
+
extra: dict[str, Any] = {}
|
|
52
|
+
if self.options.sleep is not None:
|
|
53
|
+
extra["sleep"] = self.options.sleep
|
|
54
|
+
self._client = Client(
|
|
55
|
+
self.profile.url,
|
|
56
|
+
self.profile.token,
|
|
57
|
+
proxy=self.options.proxy,
|
|
58
|
+
ca_bundle=self.options.ca_bundle,
|
|
59
|
+
verbose=self.options.verbose,
|
|
60
|
+
transport=self.options.transport,
|
|
61
|
+
**extra,
|
|
62
|
+
)
|
|
63
|
+
if not self._checked:
|
|
64
|
+
self._checked = True
|
|
65
|
+
version_check.check(self._client, self.output)
|
|
66
|
+
return self._client
|
|
67
|
+
|
|
68
|
+
def signed_in(self) -> Client:
|
|
69
|
+
if not self.profile.token:
|
|
70
|
+
raise CliError(
|
|
71
|
+
Exit.SIGNED_OUT,
|
|
72
|
+
"Вы не вошли.",
|
|
73
|
+
"Войдите: orangehack login (в CI задайте ORANGEHACK_TOKEN)",
|
|
74
|
+
code="signed_out",
|
|
75
|
+
)
|
|
76
|
+
return self.client
|
|
77
|
+
|
|
78
|
+
def sleep(self, seconds: float) -> None:
|
|
79
|
+
if self.options.sleep is not None:
|
|
80
|
+
self.options.sleep(seconds)
|
|
81
|
+
else:
|
|
82
|
+
import time
|
|
83
|
+
|
|
84
|
+
time.sleep(seconds)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def options_of(ctx: typer.Context) -> Options:
|
|
88
|
+
root = ctx.find_root()
|
|
89
|
+
if isinstance(root.obj, Options):
|
|
90
|
+
return root.obj
|
|
91
|
+
return Options()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def execute(ctx: typer.Context, json_flag: bool, body: Callable[[Session], None]) -> None:
|
|
95
|
+
options = options_of(ctx)
|
|
96
|
+
output = Output(json_mode=json_flag or options.json)
|
|
97
|
+
session: Session | None = None
|
|
98
|
+
try:
|
|
99
|
+
session = Session(options, output, config.load(options.profile, options.url))
|
|
100
|
+
body(session)
|
|
101
|
+
except CliError as error:
|
|
102
|
+
output.error(error)
|
|
103
|
+
raise typer.Exit(int(error.exit)) from None
|
|
104
|
+
except LostAnswer:
|
|
105
|
+
lost = CliError(Exit.NETWORK, "Связь оборвалась, ответ платформы не получен.")
|
|
106
|
+
output.error(lost)
|
|
107
|
+
raise typer.Exit(int(lost.exit)) from None
|
|
108
|
+
except KeyboardInterrupt:
|
|
109
|
+
output.note("Прервано.")
|
|
110
|
+
raise typer.Exit(130) from None
|
|
111
|
+
except (typer.Exit, typer.Abort):
|
|
112
|
+
raise
|
|
113
|
+
except Exception as exc: # the exit-code contract holds for what we did not foresee too
|
|
114
|
+
if options.verbose:
|
|
115
|
+
traceback.print_exc(file=sys.stderr)
|
|
116
|
+
unexpected = CliError(
|
|
117
|
+
Exit.NETWORK,
|
|
118
|
+
f"Неожиданная ошибка: {type(exc).__name__}: {exc}",
|
|
119
|
+
"Повторите команду; если повторяется, запустите с --verbose "
|
|
120
|
+
"и пришлите вывод организаторам платформы.",
|
|
121
|
+
code="unexpected",
|
|
122
|
+
)
|
|
123
|
+
output.error(unexpected)
|
|
124
|
+
raise typer.Exit(int(unexpected.exit)) from None
|
|
125
|
+
finally:
|
|
126
|
+
if session is not None and session._client is not None:
|
|
127
|
+
session._client.close()
|