Spaces:
Runtime error

File size: 4,505 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env python3
"""Sync a Render service environment variable through Render API.

Examples:
  python scripts/sync_render_env_var.py \
    --service-id srv-xxxxxxxx \
    --api-key rnda_xxxxx \
    --key DESKTOP_APP_LATEST_VERSION \
    --value 1.0.2

  python scripts/sync_render_env_var.py \
    --service-id srv-xxxxxxxx \
    --api-key rnda_xxxxx \
    --key DESKTOP_APP_LATEST_VERSION \
    --value-from-build-info desktop/app/build_info.py
"""

from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Update a Render env var")
    parser.add_argument("--service-id", required=True, help="Render service ID (srv-...)")
    parser.add_argument("--api-key", required=True, help="Render API key")
    parser.add_argument("--key", required=True, help="Environment variable name")
    parser.add_argument("--value", default="", help="New value for env var")
    parser.add_argument(
        "--value-from-build-info",
        default="",
        help="Path to build_info.py containing DESKTOP_APP_VERSION",
    )
    parser.add_argument("--base-url", default="https://api.render.com/v1", help="Render API base URL")
    return parser.parse_args()


def read_version_from_build_info(path: Path) -> str:
    content = path.read_text(encoding="utf-8", errors="ignore")
    match = re.search(r'DESKTOP_APP_VERSION\s*=\s*"([^"]+)"', content)
    if not match:
        raise ValueError("DESKTOP_APP_VERSION not found in build_info.py")
    return str(match.group(1)).strip()


def update_env_var(base_url: str, service_id: str, api_key: str, key: str, value: str) -> dict:
    endpoint = f"{base_url.rstrip('/')}/services/{quote(service_id)}/env-vars/{quote(key)}"
    payload = json.dumps({"value": value}).encode("utf-8")
    req = Request(
        endpoint,
        method="PUT",
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "ai-tester-platform/render-env-sync",
        },
        data=payload,
    )
    with urlopen(req, timeout=20) as response:
        body = response.read().decode("utf-8", errors="ignore").strip()
        if not body:
            return {"ok": True, "status": int(getattr(response, "status", 200) or 200)}
        try:
            parsed = json.loads(body)
        except Exception:
            parsed = {"raw": body}
        parsed["ok"] = True
        return parsed


def main() -> int:
    args = parse_args()
    value = str(args.value or "").strip()

    if not value and args.value_from_build_info:
        build_info_path = Path(args.value_from_build_info).expanduser().resolve()
        if not build_info_path.exists():
            raise SystemExit(f"Build info file not found: {build_info_path}")
        value = read_version_from_build_info(build_info_path)

    if not value:
        raise SystemExit("Missing value. Provide --value or --value-from-build-info.")

    try:
        result = update_env_var(
            base_url=str(args.base_url),
            service_id=str(args.service_id),
            api_key=str(args.api_key),
            key=str(args.key),
            value=value,
        )
        print(json.dumps({"ok": True, "key": args.key, "value": value, "result": result}, ensure_ascii=True))
        return 0
    except HTTPError as exc:
        error_body = ""
        try:
            error_body = exc.read().decode("utf-8", errors="ignore")
        except Exception:
            error_body = str(exc)
        print(
            json.dumps(
                {
                    "ok": False,
                    "error": f"HTTP {exc.code}",
                    "detail": error_body[:800],
                    "key": args.key,
                    "value": value,
                },
                ensure_ascii=True,
            ),
            file=sys.stderr,
        )
        return 1
    except URLError as exc:
        print(json.dumps({"ok": False, "error": f"Network error: {exc}"}, ensure_ascii=True), file=sys.stderr)
        return 1
    except Exception as exc:
        print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=True), file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())