Files
ai-engineering/scripts/build-sqlite-cli.py
T

58 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""Build the pinned diagnostic CLI in build/, never install it."""
import hashlib
import json
import os
import platform
from pathlib import Path
import subprocess
import sys
import urllib.request
import zipfile
destination = Path(sys.argv[1]).resolve()
destination.mkdir(parents=True, exist_ok=True)
pin = json.loads(Path(__file__).with_name("sqlite-version.json").read_text())
if sys.platform == "win32":
if platform.machine().lower() not in ("amd64", "x86_64"):
raise SystemExit("The native Windows package currently requires x64")
archive = destination / "sqlite-tools-win-x64.zip"
if not archive.exists():
urllib.request.urlretrieve(pin["windows_url"], archive)
if hashlib.sha3_256(archive.read_bytes()).hexdigest() != pin["windows_sha3_256"]:
raise SystemExit("SQLite Windows package checksum differs from the official pin")
with zipfile.ZipFile(archive) as bundle:
names = [name for name in bundle.namelist() if name.rsplit("/", 1)[-1] == "sqlite3.exe"]
if len(names) != 1:
raise SystemExit("SQLite package lacks an unambiguous sqlite3.exe")
(destination / "sqlite3.exe").write_bytes(bundle.read(names[0]))
version = subprocess.check_output([str(destination / "sqlite3.exe"), "--version"], text=True).split()[0]
if version != pin["version"]:
raise SystemExit("SQLite Windows package version differs from the pin")
sys.exit(0)
archive = destination / pin["archive"]
if not archive.exists():
temporary = archive.with_suffix(".download")
urllib.request.urlretrieve(pin["url"], temporary)
temporary.replace(archive)
if hashlib.sha3_256(archive.read_bytes()).hexdigest() != pin["sha3_256"]:
raise SystemExit("SQLite source checksum differs from the pinned official release")
source = destination / "source"
source.mkdir(exist_ok=True)
with zipfile.ZipFile(archive) as bundle:
prefix = pin["archive"].removesuffix(".zip") + "/"
for name in ("sqlite3.c", "sqlite3.h", "sqlite3ext.h", "shell.c"):
(source / name).write_bytes(bundle.read(prefix + name))
binary = destination / "sqlite3"
temporary = destination / "sqlite3.new"
command = [os.environ.get("CC", "cc"), "-O2", "-DSQLITE_THREADSAFE=1", "-DSQLITE_DQS=0",
str(source / "shell.c"), str(source / "sqlite3.c"), "-o", str(temporary), "-lm", "-lpthread"]
if sys.platform.startswith("linux"):
command.append("-ldl")
subprocess.run(command, check=True)
version = subprocess.check_output([str(temporary), "--version"], text=True).split()[0]
if version != pin["version"]:
raise SystemExit("Compiled SQLite version differs from the pin")
temporary.replace(binary)
print("Built SQLite", version, "in", destination)