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
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"""`submit`: the same upload ticket and submit endpoints as the site, with integrity checks.
|
|
2
|
+
|
|
3
|
+
Order: choose the deliverable -> check the size against its limit -> SHA-256 of the local bytes ->
|
|
4
|
+
upload ticket -> signed PUT -> complete -> wait until the platform checked the file -> submit once
|
|
5
|
+
-> compare `content_hash`. A submit whose answer was lost is never sent again: the history is read
|
|
6
|
+
and the version with the same hash, if any, is reported.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Annotated, Any
|
|
16
|
+
|
|
17
|
+
import typer
|
|
18
|
+
|
|
19
|
+
from .. import resolve, transfer
|
|
20
|
+
from ..errors import CliError, Exit, LostAnswer
|
|
21
|
+
from ..session import JsonOpt, Session, execute
|
|
22
|
+
from .attempts import STATES, attempt_of, wait_for_score
|
|
23
|
+
from .competitions import case_keys, overview_of
|
|
24
|
+
|
|
25
|
+
FILE_TYPES = ("file", "archive")
|
|
26
|
+
UPLOAD_CHECK_SECONDS = 180
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _kind(paths: list[Path], text: str | None, url: str | None) -> str:
|
|
30
|
+
given = sum(bool(x) for x in (paths, text is not None, url is not None))
|
|
31
|
+
if given != 1:
|
|
32
|
+
raise CliError(
|
|
33
|
+
Exit.USAGE,
|
|
34
|
+
"Сдайте что-то одно: файлы, --text или --url.",
|
|
35
|
+
"Например: orangehack submit org/contest submission.csv",
|
|
36
|
+
)
|
|
37
|
+
return "file" if paths else ("text" if text is not None else "url")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _accepts(d: resolve.Deliverable, kind: str) -> bool:
|
|
41
|
+
if kind == "file":
|
|
42
|
+
return d.type in FILE_TYPES
|
|
43
|
+
return d.type == kind
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def choose(
|
|
47
|
+
s: Session,
|
|
48
|
+
target: resolve.Competition,
|
|
49
|
+
kind: str,
|
|
50
|
+
case: str | None,
|
|
51
|
+
deliverable: str | None,
|
|
52
|
+
) -> resolve.Deliverable:
|
|
53
|
+
overview = overview_of(s, target)
|
|
54
|
+
items = resolve.narrow(
|
|
55
|
+
resolve.deliverables(overview),
|
|
56
|
+
case=case,
|
|
57
|
+
deliverable=deliverable,
|
|
58
|
+
case_keys=case_keys(s, target) if case else None,
|
|
59
|
+
)
|
|
60
|
+
if deliverable:
|
|
61
|
+
return resolve.one(items)
|
|
62
|
+
fitting = [d for d in items if _accepts(d, kind)]
|
|
63
|
+
open_now = [d for d in fitting if d.open]
|
|
64
|
+
if len(open_now) == 1:
|
|
65
|
+
return open_now[0]
|
|
66
|
+
if len(open_now) > 1:
|
|
67
|
+
raise resolve.ambiguous("открытых сдач", open_now)
|
|
68
|
+
if len(fitting) == 1:
|
|
69
|
+
return fitting[0] # closed: the platform says why and stores the refusal
|
|
70
|
+
if fitting:
|
|
71
|
+
raise resolve.ambiguous("сдач", fitting)
|
|
72
|
+
raise CliError(
|
|
73
|
+
Exit.LIMIT,
|
|
74
|
+
"Сейчас нет открытой сдачи такого типа.",
|
|
75
|
+
f"Посмотрите сроки: orangehack deliverables {target.address}",
|
|
76
|
+
code="nothing_open",
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _ticket(data: dict[str, Any]) -> transfer.Ticket:
|
|
81
|
+
return transfer.Ticket(
|
|
82
|
+
file_id=str(data["file_id"]),
|
|
83
|
+
url=str(data["url"]),
|
|
84
|
+
method=str(data.get("method") or "PUT"),
|
|
85
|
+
headers={str(k): str(v) for k, v in (data.get("headers") or {}).items()},
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def upload(s: Session, competition_id: str, deliverable_id: str, path: Path, name: str) -> str:
|
|
90
|
+
"""Upload a file and wait until the platform checked it; returns the file id."""
|
|
91
|
+
base = f"/api/v1/deliverables/competitions/{competition_id}"
|
|
92
|
+
size = path.stat().st_size
|
|
93
|
+
|
|
94
|
+
def begin() -> transfer.Ticket:
|
|
95
|
+
return _ticket(
|
|
96
|
+
s.client.post(
|
|
97
|
+
f"{base}/deliverables/{deliverable_id}/uploads", {"filename": name, "size": size}
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def progress(sent: int, total: int) -> None:
|
|
102
|
+
percent = int(sent * 100 / total) if total else 100
|
|
103
|
+
s.output.progress(f"Отправка {name}: {percent}% ({_mb(sent)} из {_mb(total)})")
|
|
104
|
+
|
|
105
|
+
ticket = transfer.put(
|
|
106
|
+
s.client.storage, begin(), path, progress=progress, sleep=s.sleep, renew=begin
|
|
107
|
+
)
|
|
108
|
+
s.output.progress_done()
|
|
109
|
+
state = s.client.post(f"{base}/uploads/{ticket.file_id}/complete")
|
|
110
|
+
started = time.monotonic()
|
|
111
|
+
while state.get("status") == "pending":
|
|
112
|
+
if s.options.sleep is None and time.monotonic() - started > UPLOAD_CHECK_SECONDS:
|
|
113
|
+
raise CliError(
|
|
114
|
+
Exit.NETWORK,
|
|
115
|
+
"Платформа долго проверяет файл.",
|
|
116
|
+
"Повторите команду через пару минут.",
|
|
117
|
+
code="file_not_ready",
|
|
118
|
+
)
|
|
119
|
+
s.sleep(1.0)
|
|
120
|
+
state = s.client.get(f"{base}/uploads/{ticket.file_id}")
|
|
121
|
+
if state.get("status") != "ready":
|
|
122
|
+
raise CliError(
|
|
123
|
+
Exit.REFUSED,
|
|
124
|
+
"Платформа не приняла файл: он не прошёл проверку.",
|
|
125
|
+
"Проверьте формат и размер (orangehack deliverables) и сдайте снова.",
|
|
126
|
+
code="upload_rejected",
|
|
127
|
+
)
|
|
128
|
+
return ticket.file_id
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
SHOWN_NAMES = 10
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _can_ask() -> bool:
|
|
135
|
+
return sys.stdin.isatty()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _show(s: Session, archive: transfer.Packed, *, asking: bool) -> None:
|
|
139
|
+
"""What went into the archive and what stayed out; the file list only when we ask."""
|
|
140
|
+
count = len(archive.names)
|
|
141
|
+
s.output.note(
|
|
142
|
+
f"Упаковано в {archive.path.name}: {count} {_files(count)}, {_mb(archive.path.stat().st_size)}."
|
|
143
|
+
)
|
|
144
|
+
if asking:
|
|
145
|
+
for name in archive.names[:SHOWN_NAMES]:
|
|
146
|
+
s.output.note(f" {name}")
|
|
147
|
+
if count > SHOWN_NAMES:
|
|
148
|
+
s.output.note(f" … и ещё {count - SHOWN_NAMES}")
|
|
149
|
+
if archive.secrets:
|
|
150
|
+
s.output.note("Не упакованы, похожи на секреты: " + ", ".join(archive.secrets))
|
|
151
|
+
if archive.links:
|
|
152
|
+
s.output.note("Не упакованы символические ссылки: " + ", ".join(archive.links))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _files(count: int) -> str:
|
|
156
|
+
if count % 10 == 1 and count % 100 != 11:
|
|
157
|
+
return "файл"
|
|
158
|
+
if count % 10 in (2, 3, 4) and count % 100 not in (12, 13, 14):
|
|
159
|
+
return "файла"
|
|
160
|
+
return "файлов"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _mb(size: int) -> str:
|
|
164
|
+
return f"{size / 1024 / 1024:.1f} МБ"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _hand_in_file(
|
|
168
|
+
s: Session,
|
|
169
|
+
competition_id: str,
|
|
170
|
+
deliverable_id: str,
|
|
171
|
+
files: list[Path],
|
|
172
|
+
limit: Any,
|
|
173
|
+
*,
|
|
174
|
+
yes: bool,
|
|
175
|
+
) -> tuple[str, str, str]:
|
|
176
|
+
"""Pack when needed, check, upload; returns (sha256, file id, file name).
|
|
177
|
+
|
|
178
|
+
A packed archive lives in a temporary folder that is removed as soon as the upload ends, sent,
|
|
179
|
+
refused or failed.
|
|
180
|
+
"""
|
|
181
|
+
with contextlib.ExitStack() as stack:
|
|
182
|
+
if len(files) > 1 or files[0].is_dir():
|
|
183
|
+
stem = files[0].resolve().name if len(files) == 1 else "submission"
|
|
184
|
+
archive = stack.enter_context(transfer.pack(files, f"{stem}.zip"))
|
|
185
|
+
path = archive.path
|
|
186
|
+
_show(s, archive, asking=not yes)
|
|
187
|
+
if not yes:
|
|
188
|
+
if not _can_ask():
|
|
189
|
+
raise CliError(
|
|
190
|
+
Exit.USAGE,
|
|
191
|
+
"Папка упакована, но подтвердить отправку некому.",
|
|
192
|
+
"Добавьте --yes, чтобы сдать без вопроса.",
|
|
193
|
+
)
|
|
194
|
+
typer.confirm("Сдать этот архив?", abort=True, err=True)
|
|
195
|
+
else:
|
|
196
|
+
path = files[0]
|
|
197
|
+
size = path.stat().st_size
|
|
198
|
+
if limit and size > int(limit) * 1024 * 1024:
|
|
199
|
+
raise CliError(
|
|
200
|
+
Exit.USAGE,
|
|
201
|
+
f"Файл {_mb(size)} больше лимита этой сдачи ({limit} МБ).",
|
|
202
|
+
code="file_too_large",
|
|
203
|
+
)
|
|
204
|
+
if size == 0:
|
|
205
|
+
raise CliError(Exit.USAGE, "Файл пустой.", code="empty_file")
|
|
206
|
+
digest = transfer.sha256_of(path)
|
|
207
|
+
return digest, upload(s, competition_id, deliverable_id, path, path.name), path.name
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
RECOVER_READS = 3
|
|
211
|
+
RECOVER_PAUSE = 5.0
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _recover(
|
|
215
|
+
s: Session,
|
|
216
|
+
target: resolve.Competition,
|
|
217
|
+
deliverable_id: str,
|
|
218
|
+
digest: str,
|
|
219
|
+
body: dict[str, Any],
|
|
220
|
+
before: set[str],
|
|
221
|
+
) -> dict[str, Any]:
|
|
222
|
+
"""After a lost answer: find the version this submit made, if it was made.
|
|
223
|
+
|
|
224
|
+
The history is read up to three times with a pause: a submit whose answer timed out may still
|
|
225
|
+
be stored a little later.
|
|
226
|
+
"""
|
|
227
|
+
for read in range(RECOVER_READS):
|
|
228
|
+
if read:
|
|
229
|
+
s.sleep(RECOVER_PAUSE)
|
|
230
|
+
try:
|
|
231
|
+
detail = s.client.get(
|
|
232
|
+
f"/api/v1/deliverables/competitions/{target.id}/deliverables/{deliverable_id}"
|
|
233
|
+
)
|
|
234
|
+
except (CliError, LostAnswer) as error:
|
|
235
|
+
raise CliError(
|
|
236
|
+
Exit.NETWORK,
|
|
237
|
+
"Связь оборвалась после отправки, и историю попыток прочитать не удалось: "
|
|
238
|
+
"сдача могла сохраниться.",
|
|
239
|
+
f"Прежде чем повторять, проверьте попытки: orangehack attempts {target.address}. "
|
|
240
|
+
"Если этой сдачи там нет, повторите команду.",
|
|
241
|
+
code="lost_answer",
|
|
242
|
+
detail=str(error),
|
|
243
|
+
) from error
|
|
244
|
+
for version in detail.get("versions", []):
|
|
245
|
+
if version["id"] in before:
|
|
246
|
+
continue
|
|
247
|
+
payload = version.get("payload") or {}
|
|
248
|
+
if (digest and transfer.same_hash(digest, version.get("content_hash", ""))) or (
|
|
249
|
+
not digest
|
|
250
|
+
and (
|
|
251
|
+
(body.get("text") is not None and payload.get("text") == body["text"])
|
|
252
|
+
or (body.get("url") is not None and payload.get("url") == body["url"])
|
|
253
|
+
)
|
|
254
|
+
):
|
|
255
|
+
s.output.note("Связь оборвалась после отправки, но сдача сохранилась на платформе.")
|
|
256
|
+
return dict(version)
|
|
257
|
+
raise CliError(
|
|
258
|
+
Exit.NETWORK,
|
|
259
|
+
"Связь оборвалась после отправки, и в истории сдача пока не появилась.",
|
|
260
|
+
f"Через пару минут проверьте попытки: orangehack attempts {target.address}. "
|
|
261
|
+
"Если этой сдачи там нет, повторите команду.",
|
|
262
|
+
code="lost_answer",
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def submit(
|
|
267
|
+
ctx: typer.Context,
|
|
268
|
+
competition: Annotated[str, typer.Argument(help="Адрес (организация/соревнование) или id.")],
|
|
269
|
+
paths: Annotated[
|
|
270
|
+
list[Path] | None,
|
|
271
|
+
typer.Argument(help="Файл; папку или несколько файлов упакуем в zip.", show_default=False),
|
|
272
|
+
] = None,
|
|
273
|
+
case: Annotated[str | None, typer.Option("--case", help="Ключ или название кейса.")] = None,
|
|
274
|
+
deliverable: Annotated[
|
|
275
|
+
str | None, typer.Option("--deliverable", "-d", help="Ключ или название сдачи.")
|
|
276
|
+
] = None,
|
|
277
|
+
text: Annotated[str | None, typer.Option("--text", help="Сдать текст.")] = None,
|
|
278
|
+
url: Annotated[str | None, typer.Option("--url", help="Сдать ссылку.")] = None,
|
|
279
|
+
name: Annotated[str | None, typer.Option("--name", help="Своё название попытки.")] = None,
|
|
280
|
+
tag: Annotated[
|
|
281
|
+
list[str] | None, typer.Option("--tag", help="Тег попытки; можно несколько.")
|
|
282
|
+
] = None,
|
|
283
|
+
wait: Annotated[bool, typer.Option("--wait", help="Дождаться оценки и места.")] = False,
|
|
284
|
+
timeout: Annotated[int, typer.Option("--timeout", help="Сколько ждать оценку, секунд.")] = 1800,
|
|
285
|
+
yes: Annotated[bool, typer.Option("--yes", "-y", help="Не спрашивать подтверждение.")] = False,
|
|
286
|
+
json_: JsonOpt = False,
|
|
287
|
+
) -> None:
|
|
288
|
+
"""Сдать решение: файл, папку (zip), текст или ссылку. С --wait — дождаться оценки."""
|
|
289
|
+
|
|
290
|
+
def body(s: Session) -> None:
|
|
291
|
+
files = list(paths or [])
|
|
292
|
+
kind = _kind(files, text, url)
|
|
293
|
+
for path in files:
|
|
294
|
+
if not path.exists():
|
|
295
|
+
raise CliError(Exit.USAGE, f"Файла {path} нет.")
|
|
296
|
+
client = s.signed_in()
|
|
297
|
+
target = resolve.competition(client, competition)
|
|
298
|
+
chosen = choose(s, target, kind, case, deliverable)
|
|
299
|
+
if not chosen.open:
|
|
300
|
+
# Told before the upload: the platform would refuse the hand-in anyway.
|
|
301
|
+
blocked = chosen.blocked or {}
|
|
302
|
+
raise CliError(
|
|
303
|
+
Exit.LIMIT,
|
|
304
|
+
blocked.get("message") or f"Приём «{chosen.title}» сейчас закрыт.",
|
|
305
|
+
"Что открыто: orangehack deliverables " + target.address,
|
|
306
|
+
code=blocked.get("code") or "window_closed",
|
|
307
|
+
)
|
|
308
|
+
base = f"/api/v1/deliverables/competitions/{target.id}/deliverables/{chosen.id}"
|
|
309
|
+
detail = client.get(base)
|
|
310
|
+
before = {v["id"] for v in detail.get("versions", [])}
|
|
311
|
+
request: dict[str, Any] = {}
|
|
312
|
+
digest = ""
|
|
313
|
+
sent_name = ""
|
|
314
|
+
if kind == "file":
|
|
315
|
+
if chosen.type not in FILE_TYPES:
|
|
316
|
+
raise CliError(Exit.USAGE, f"«{chosen.title}» сдаётся не файлом, а: {chosen.type}.")
|
|
317
|
+
digest, request["file_id"], sent_name = _hand_in_file(
|
|
318
|
+
s, target.id, chosen.id, files, detail.get("max_mb"), yes=yes
|
|
319
|
+
)
|
|
320
|
+
elif kind == "text":
|
|
321
|
+
request["text"] = text
|
|
322
|
+
else:
|
|
323
|
+
request["url"] = url
|
|
324
|
+
if name:
|
|
325
|
+
request["name"] = name
|
|
326
|
+
if tag:
|
|
327
|
+
request["tags"] = list(tag)
|
|
328
|
+
try:
|
|
329
|
+
version = client.post(f"{base}/submit", request, once=True)
|
|
330
|
+
except LostAnswer:
|
|
331
|
+
version = _recover(s, target, chosen.id, digest, request, before)
|
|
332
|
+
result: dict[str, Any] = {
|
|
333
|
+
"competition": target.__dict__,
|
|
334
|
+
"deliverable": {"id": chosen.id, "key": chosen.key, "title": chosen.title},
|
|
335
|
+
"version": version,
|
|
336
|
+
}
|
|
337
|
+
refused = version.get("status") == "rejected_by_rule"
|
|
338
|
+
if (
|
|
339
|
+
digest
|
|
340
|
+
and not refused
|
|
341
|
+
and not transfer.same_hash(digest, version.get("content_hash", ""))
|
|
342
|
+
):
|
|
343
|
+
raise CliError(
|
|
344
|
+
Exit.NETWORK,
|
|
345
|
+
f"Платформа сохранила не те байты, что лежат в {sent_name}: контрольные суммы расходятся.",
|
|
346
|
+
"Сдайте файл ещё раз.",
|
|
347
|
+
code="hash_mismatch",
|
|
348
|
+
extra={"local_sha256": digest, "content_hash": version.get("content_hash")},
|
|
349
|
+
)
|
|
350
|
+
if refused:
|
|
351
|
+
refusal = version.get("refusal") or {}
|
|
352
|
+
raise CliError(
|
|
353
|
+
Exit.REFUSED,
|
|
354
|
+
refusal.get("message") or "Платформа отклонила попытку.",
|
|
355
|
+
"Попытка сохранена в истории как отклонённая.",
|
|
356
|
+
code=refusal.get("code") or "rejected_by_rule",
|
|
357
|
+
extra={"version": version},
|
|
358
|
+
)
|
|
359
|
+
attempt = attempt_of(s, chosen.id, str(version["id"]))
|
|
360
|
+
if attempt:
|
|
361
|
+
result["attempt"] = attempt
|
|
362
|
+
label = f", попытка {attempt['uid']}" if attempt and attempt.get("uid") else ""
|
|
363
|
+
s.output.say(
|
|
364
|
+
f"Сдано: «{chosen.title}», версия {version.get('version')}{label}, "
|
|
365
|
+
f"статус: {STATES.get(attempt.get('state', '') if attempt else '', 'принята')}."
|
|
366
|
+
)
|
|
367
|
+
s.output.say(f"Id версии: {version.get('id')}")
|
|
368
|
+
if wait:
|
|
369
|
+
result["score"] = wait_for_score(s, target, chosen, str(version["id"]), timeout)
|
|
370
|
+
s.output.result(result)
|
|
371
|
+
|
|
372
|
+
execute(ctx, json_, body)
|
orangehack/config.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Profiles in one TOML file, the token in the system keyring or a file only the user can read.
|
|
2
|
+
|
|
3
|
+
`ORANGEHACK_TOKEN` and `ORANGEHACK_URL` win over the file, which is what CI jobs and notebooks use;
|
|
4
|
+
with them set nothing is written. `ORANGEHACK_CONFIG_DIR` moves the file (tests, shared machines).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
|
|
17
|
+
import platformdirs
|
|
18
|
+
|
|
19
|
+
from .errors import CliError, Exit
|
|
20
|
+
|
|
21
|
+
if sys.version_info >= (3, 11):
|
|
22
|
+
import tomllib
|
|
23
|
+
else: # pragma: no cover - Python 3.10
|
|
24
|
+
import tomli as tomllib
|
|
25
|
+
|
|
26
|
+
DEFAULT_URL = "https://app.orangehack.ru"
|
|
27
|
+
DEFAULT_PROFILE = "default"
|
|
28
|
+
KEYRING_SERVICE = "orangehack"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def config_dir() -> Path:
|
|
32
|
+
override = os.environ.get("ORANGEHACK_CONFIG_DIR")
|
|
33
|
+
return Path(override) if override else Path(platformdirs.user_config_dir("orangehack"))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cache_dir() -> Path:
|
|
37
|
+
override = os.environ.get("ORANGEHACK_CACHE_DIR")
|
|
38
|
+
return Path(override) if override else Path(platformdirs.user_cache_dir("orangehack"))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def config_path() -> Path:
|
|
42
|
+
return config_dir() / "config.toml"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Profile:
|
|
47
|
+
name: str
|
|
48
|
+
url: str = DEFAULT_URL
|
|
49
|
+
token: str = field(default="", repr=False)
|
|
50
|
+
token_id: str = ""
|
|
51
|
+
scopes: list[str] = field(default_factory=list)
|
|
52
|
+
# Where the token came from: "env", "keyring", "file" or "" (none).
|
|
53
|
+
source: str = ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _read() -> dict[str, Any]:
|
|
57
|
+
path = config_path()
|
|
58
|
+
if not path.is_file():
|
|
59
|
+
return {}
|
|
60
|
+
with path.open("rb") as handle:
|
|
61
|
+
data: dict[str, Any] = tomllib.load(handle)
|
|
62
|
+
return data
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _quote(value: str) -> str:
|
|
66
|
+
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
|
|
67
|
+
return f'"{escaped}"'
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _dump(data: dict[str, Any]) -> str:
|
|
71
|
+
"""The small TOML this file needs: top-level strings and `[profiles.<name>]` tables."""
|
|
72
|
+
lines = []
|
|
73
|
+
for key, value in data.items():
|
|
74
|
+
if isinstance(value, str):
|
|
75
|
+
lines.append(f"{key} = {_quote(value)}")
|
|
76
|
+
for name, profile in data.get("profiles", {}).items():
|
|
77
|
+
lines.append("")
|
|
78
|
+
lines.append(f"[profiles.{_quote(name)}]")
|
|
79
|
+
for key, value in profile.items():
|
|
80
|
+
if isinstance(value, list):
|
|
81
|
+
lines.append(f"{key} = [{', '.join(_quote(str(v)) for v in value)}]")
|
|
82
|
+
else:
|
|
83
|
+
lines.append(f"{key} = {_quote(str(value))}")
|
|
84
|
+
return "\n".join(lines) + "\n"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _write(data: dict[str, Any]) -> None:
|
|
88
|
+
path = config_path()
|
|
89
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
90
|
+
# 0600 before any byte is written: the file may hold the token. A new file is created so; an
|
|
91
|
+
# existing one (perhaps 0644) is narrowed through its descriptor before the write. Windows has
|
|
92
|
+
# no fchmod: the profile directory's ACL protects the file there.
|
|
93
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
94
|
+
if hasattr(os, "fchmod"):
|
|
95
|
+
os.fchmod(descriptor, 0o600)
|
|
96
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
97
|
+
handle.write(_dump(data))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _keyring() -> Any | None:
|
|
101
|
+
"""The keyring module when it is installed and has a working backend, else None."""
|
|
102
|
+
if os.environ.get("ORANGEHACK_NO_KEYRING") == "1":
|
|
103
|
+
return None
|
|
104
|
+
try:
|
|
105
|
+
import keyring
|
|
106
|
+
from keyring.backends import fail
|
|
107
|
+
except Exception:
|
|
108
|
+
return None
|
|
109
|
+
try:
|
|
110
|
+
if isinstance(keyring.get_keyring(), fail.Keyring):
|
|
111
|
+
return None
|
|
112
|
+
except Exception:
|
|
113
|
+
return None
|
|
114
|
+
return keyring
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _account(name: str, url: str) -> str:
|
|
118
|
+
return f"{name}@{url}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def profile_name(requested: str | None) -> str:
|
|
122
|
+
if requested:
|
|
123
|
+
return requested
|
|
124
|
+
env = os.environ.get("ORANGEHACK_PROFILE")
|
|
125
|
+
if env:
|
|
126
|
+
return env
|
|
127
|
+
return str(_read().get("default_profile", DEFAULT_PROFILE))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def checked_url(url: str) -> str:
|
|
134
|
+
"""The platform address: https, or plain http only on this machine (a local platform).
|
|
135
|
+
|
|
136
|
+
The token goes with every call, so it never travels unencrypted across a network."""
|
|
137
|
+
parts = urlsplit(url)
|
|
138
|
+
local = parts.hostname in LOCAL_HOSTS
|
|
139
|
+
if parts.hostname and (parts.scheme == "https" or (parts.scheme == "http" and local)):
|
|
140
|
+
return url.rstrip("/")
|
|
141
|
+
raise CliError(
|
|
142
|
+
Exit.USAGE,
|
|
143
|
+
f"Адрес платформы {url} не подходит: нужен https://.",
|
|
144
|
+
"Проверьте --url, ORANGEHACK_URL или профиль; http:// можно только для localhost.",
|
|
145
|
+
code="bad_url",
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def load(requested: str | None = None, url: str | None = None) -> Profile:
|
|
150
|
+
"""The active profile with the environment applied on top."""
|
|
151
|
+
name = profile_name(requested)
|
|
152
|
+
stored = _read().get("profiles", {}).get(name, {})
|
|
153
|
+
profile = Profile(
|
|
154
|
+
name=name,
|
|
155
|
+
url=checked_url(
|
|
156
|
+
url or os.environ.get("ORANGEHACK_URL") or stored.get("url") or DEFAULT_URL
|
|
157
|
+
),
|
|
158
|
+
token_id=str(stored.get("token_id", "")),
|
|
159
|
+
scopes=list(stored.get("scopes", [])),
|
|
160
|
+
)
|
|
161
|
+
env_token = os.environ.get("ORANGEHACK_TOKEN", "").strip()
|
|
162
|
+
if env_token:
|
|
163
|
+
profile.token, profile.source = env_token, "env"
|
|
164
|
+
return profile
|
|
165
|
+
if stored.get("url") and stored.get("url").rstrip("/") != profile.url:
|
|
166
|
+
return profile # the stored token belongs to another platform address
|
|
167
|
+
if stored.get("token"):
|
|
168
|
+
profile.token, profile.source = str(stored["token"]), "file"
|
|
169
|
+
return profile
|
|
170
|
+
if stored.get("keyring"):
|
|
171
|
+
backend = _keyring()
|
|
172
|
+
secret = (
|
|
173
|
+
backend.get_password(KEYRING_SERVICE, _account(name, profile.url)) if backend else None
|
|
174
|
+
)
|
|
175
|
+
if secret:
|
|
176
|
+
profile.token, profile.source = secret, "keyring"
|
|
177
|
+
return profile
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def save(profile: Profile, token: str) -> str:
|
|
181
|
+
"""Store the token for the profile; returns where it went ("keyring" or the file path)."""
|
|
182
|
+
data = _read()
|
|
183
|
+
profiles = data.setdefault("profiles", {})
|
|
184
|
+
entry: dict[str, Any] = {
|
|
185
|
+
"url": profile.url,
|
|
186
|
+
"token_id": profile.token_id,
|
|
187
|
+
"scopes": profile.scopes,
|
|
188
|
+
}
|
|
189
|
+
backend = _keyring()
|
|
190
|
+
where = str(config_path())
|
|
191
|
+
if backend is not None:
|
|
192
|
+
try:
|
|
193
|
+
backend.set_password(KEYRING_SERVICE, _account(profile.name, profile.url), token)
|
|
194
|
+
entry["keyring"] = "yes"
|
|
195
|
+
where = "keyring"
|
|
196
|
+
except Exception:
|
|
197
|
+
entry["token"] = token
|
|
198
|
+
else:
|
|
199
|
+
entry["token"] = token
|
|
200
|
+
profiles[profile.name] = entry
|
|
201
|
+
data.setdefault("default_profile", profile.name)
|
|
202
|
+
_write(data)
|
|
203
|
+
return where
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def forget(profile: Profile) -> bool:
|
|
207
|
+
"""Remove the stored token of the profile; True when there was one."""
|
|
208
|
+
data = _read()
|
|
209
|
+
entry = data.get("profiles", {}).get(profile.name)
|
|
210
|
+
if not entry:
|
|
211
|
+
return False
|
|
212
|
+
if entry.get("keyring"):
|
|
213
|
+
backend = _keyring()
|
|
214
|
+
if backend is not None:
|
|
215
|
+
with contextlib.suppress(Exception):
|
|
216
|
+
backend.delete_password(KEYRING_SERVICE, _account(profile.name, profile.url))
|
|
217
|
+
had = bool(entry.get("token") or entry.get("keyring"))
|
|
218
|
+
for key in ("token", "keyring", "token_id", "scopes"):
|
|
219
|
+
entry.pop(key, None)
|
|
220
|
+
_write(data)
|
|
221
|
+
return had
|