File size: 1,879 Bytes
d0eee72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Tiny client for pushing traces to a tracebin Space.

    from tracebin import share

    url = share(messages, title="run 41")
    print(url)

Configure with environment variables:

    TRACEBIN_URL     https://your-space.hf.space
    TRACEBIN_TOKEN   upload token, if the Space sets one
"""

from __future__ import annotations

import json
import os
import urllib.error
import urllib.request
from typing import Any


class TracebinError(RuntimeError):
    pass


def share(
    trace: Any,
    title: str = "",
    base_url: str | None = None,
    token: str | None = None,
    timeout: float = 30.0,
) -> str:
    """Upload ``trace`` and return its secret URL.

    The returned URL is the only way to reach the trace — nothing lists it.
    Treat it like a password: don't print it into shared logs.
    """
    base_url = (base_url or os.environ.get("TRACEBIN_URL", "")).rstrip("/")
    if not base_url:
        raise TracebinError("set TRACEBIN_URL or pass base_url=")
    token = token if token is not None else os.environ.get("TRACEBIN_TOKEN", "")

    body = json.dumps({"title": title, "trace": trace}, default=str).encode("utf-8")
    request = urllib.request.Request(
        f"{base_url}/api/traces",
        data=body,
        method="POST",
        headers={"content-type": "application/json"},
    )
    if token:
        request.add_header("x-upload-token", token)

    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return json.loads(response.read())["url"]
    except urllib.error.HTTPError as exc:
        raise TracebinError(f"{exc.code}: {exc.read().decode('utf-8', 'replace')}") from exc


if __name__ == "__main__":
    import sys

    data = sys.stdin.read()
    try:
        payload = json.loads(data)
    except ValueError:
        payload = data
    print(share(payload, title=" ".join(sys.argv[1:])))