File size: 4,657 Bytes
b727f11
 
 
 
 
 
 
5423dad
b727f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1b51ae
b727f11
 
 
 
5423dad
 
b727f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1b51ae
 
 
 
5423dad
 
 
 
 
b727f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Install the pinned private submodule at runtime, before importing Gradio."""

import argparse
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile

ROOT = Path(__file__).resolve().parent
REPOSITORY = "https://github.com/edmcman/decompile-verify.git"


def revision():
    data = json.loads((ROOT / "core-revision.json").read_text())
    if data["repository"] != REPOSITORY or not re.fullmatch(r"[0-9a-f]{40}", data["commit"]):
        raise ValueError("invalid pinned core repository or commit")
    return data


def command(args, *, env=None, cwd=None, timeout=300):
    try:
        return subprocess.run(args, cwd=cwd, env=env, check=True, capture_output=True,
                              text=True, timeout=timeout).stdout.strip()
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError) as error:
        # Never emit raw Git output or the authentication environment into Space logs.
        raise RuntimeError(f"private core setup failed during {Path(args[0]).name}; "
                           "check repository access, pinned commit, native toolchain, and network availability") from error


def install_core():
    pinned = revision()
    if (ROOT / "core/.git").exists():
        raise RuntimeError("core checkout already exists; use the local development entry point")
    token = os.environ.pop("CORE_GITHUB_TOKEN", None)
    if not token:
        raise RuntimeError("set the CORE_GITHUB_TOKEN Space secret to a read-only GitHub token")
    clean_env = {key: value for key, value in os.environ.items()
                 if not key.startswith("GIT_")}
    clean_env["GIT_TERMINAL_PROMPT"] = "0"
    clean_env["GIT_CONFIG_GLOBAL"] = os.devnull
    clean_env["GIT_CONFIG_NOSYSTEM"] = "1"
    # An ephemeral askpass helper supplies the credential without storing it in
    # a URL, git config, command line, or the environment of the running app.
    with tempfile.TemporaryDirectory(prefix="private-core-") as temporary:
        directory = Path(temporary)
        askpass = directory / "askpass.py"
        askpass.write_text(f"#!{sys.executable}\nimport os, sys\n"
                           "print('x-access-token' if 'username' in sys.argv[1].lower() "
                           "else os.environ['CORE_GITHUB_TOKEN'])\n")
        askpass.chmod(0o700)
        git_env = {**clean_env, "GIT_ASKPASS": str(askpass), "CORE_GITHUB_TOKEN": token}
        # Disable credential helpers so no persistent credential is read or saved.
        git_env.update(GIT_CONFIG_COUNT="1", GIT_CONFIG_KEY_0="credential.helper", GIT_CONFIG_VALUE_0="")
        source = directory / "source"
        source.mkdir()
        command(["git", "init", "--quiet", str(source)], env=clean_env)
        command(["git", "remote", "add", "origin", REPOSITORY], env=clean_env, cwd=source)
        command(["git", "fetch", "--quiet", "--depth=1", "origin", pinned["commit"]], env=git_env, cwd=source)
        fetched = command(["git", "rev-parse", "FETCH_HEAD"], env=clean_env, cwd=source)
        if fetched != pinned["commit"]:
            raise RuntimeError("fetched core revision differs from the pinned submodule")
        command(["git", "checkout", "--quiet", "--detach", "FETCH_HEAD"], env=clean_env, cwd=source)
        git_env.clear()
        token = None
        command(["uv", "pip", "install", "--python", sys.executable,
                 "--no-deps", "--no-build-isolation", str(source)], env=clean_env)
        helper = Path(sys.executable).parent / "decompile-verify-declarations"
        command(["bash", str(source / "native/build.sh"), str(helper)],
                env=clean_env, cwd=source)
        command([str(helper), "--version"], env=clean_env)
        shutil.rmtree(source / ".git")
        destination = ROOT / "core"
        if destination.exists():
            shutil.rmtree(destination)
        shutil.move(str(source), str(destination))
    from importlib.metadata import version
    if version("decompile-verify") != pinned["version"]:
        raise RuntimeError("installed core version differs from the pinned metadata")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--install-only", action="store_true")
    args = parser.parse_args()
    try:
        install_core()
    except (RuntimeError, ValueError, KeyError, OSError) as error:
        print(str(error), file=sys.stderr)
        return 1
    if not args.install_only:
        os.execv(sys.executable, [sys.executable, "-m", "demo.app", "--host", "0.0.0.0", "--port", "7860"])
    return 0


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