Files
ports/lib/managed_source.py
T
2026-10-28 08:02:52 +00:00

177 lines
6.9 KiB
Python

import os
import subprocess
import glob
import urllib.request
import json
from urllib.parse import urlparse
from . import sources
DEFAULT_REPO="https://mirror1.semilabs.org/semios/sources"
def postprocess_rust():
subprocess.run(["cargo", "vendor"], check=True)
os.makedirs(".cargo", exist_ok=True)
with open(".cargo/config.toml", "a+") as fd:
fd.write(
"[source.crates-io]\nreplace-with = 'vendored-sources'\n[source.vendored-sources]\ndirectory = 'vendor'\n",
)
def postprocess_autotools():
if os.path.exists("autogen.sh"):
subprocess.run(["sh", "autogen.sh"], check=True)
else:
subprocess.run(["autoreconf", "-fiv"], check=True)
subprocess.run(["./configure"], check=False)
subprocess.run(["make", "dist"], check=True)
tarballs = glob.glob("*.tar.*z")
if len(tarballs) == 0:
raise RuntimeError("No dist tarballs found.")
subprocess.run(["tar", "xf", tarballs[0]], check=True)
os.chdir(tarballs[0].replace(".tar.gz", "").replace(".tar.xz", ""))
def postprocess_go():
subprocess.run(["go", "mod", "vendor"], check=True)
def get_origin_url(s):
url = urlparse(s)
if url.scheme == "github":
return f"https://github.com/{url.hostname}{url.path}/archive/refs/tags/{url.fragment}.tar.gz"
elif url.scheme == "gitea":
return f"https://{url.hostname}{url.path}/archive/{url.fragment}.tar.gz"
elif url.scheme == "gitlab":
return f"https://{url.hostname}/{url.path}/-/archive/{url.fragment}/{url.path.split('/')[1]}-{url.fragment}.tar.gz"
elif url.scheme == "srht":
return f"https://{url.hostname}/{url.path}/archive/{url.fragment}.tar.gz"
elif url.scheme == "pypi":
pkgname = url.hostname
return f"https://files.pythonhosted.org/packages/source/{pkgname[0]}/{pkgname}/{pkgname}-{url.fragment}.tar.gz"
else:
raise RuntimeError(f"Unsupported scheme \"{url.scheme}\"")
def get_updates(s):
user_agent = "SemiOS Ports Update Checker"
url = urlparse(s)
if url.scheme == "github":
current_version = url.fragment
api_url = f"https://api.github.com/repos/{url.hostname}{url.path}/releases/latest"
api_req = urllib.request.Request(api_url, headers = {
"Accept": "application/vnd.github+json",
"User-Agent": user_agent,
})
try:
with urllib.request.urlopen(api_req) as resp:
release = json.load(resp)
except Exception as err:
return "[INVALID] Failed to fetch releases: " + str(err)
latest = release["tag_name"]
if latest == current_version:
return "[OK] Already the latest."
return "[OLD] Version is old, latest is " + latest
elif url.scheme == "gitea":
current_version = url.fragment
api_url = f"https://{url.hostname}/api/v1/repos{url.path}/releases/latest"
api_req = urllib.request.Request(api_url, headers = {
"Accept": "application/json",
"User-Agent": user_agent,
})
try:
with urllib.request.urlopen(api_req) as resp:
release = json.load(resp)
except Exception as err:
return "[INVALID] Failed to fetch releases: " + str(err)
latest = release["tag_name"]
if latest == current_version:
return "[OK] Already the latest."
return "[OLD] Version is old, latest is " + latest
elif url.scheme == "gitlab":
current_version = url.fragment
project_path = url.path.strip("/")
encoded_path = urllib.parse.quote(project_path, safe='')
api_url = f"https://{url.hostname}/api/v4/projects/{encoded_path}/repository/tags?per_page=1"
api_req = urllib.request.Request(api_url, headers={
"Accept": "application/json",
"User-Agent": user_agent,
})
try:
with urllib.request.urlopen(api_req) as resp:
tags = json.load(resp)
except Exception as err:
return "[INVALID] Failed to fetch tags: " + str(err)
if not tags:
return "[INVALID] No tags found."
latest = tags[0]["name"]
if latest == current_version:
return "[OK] Already the latest."
return "[OLD] Version is old, latest is " + latest
elif url.scheme == "pypi":
current_version = url.fragment
package_name = url.hostname
api_url = f"https://pypi.org/pypi/{package_name}/json"
api_req = urllib.request.Request(api_url, headers={
"Accept": "application/json",
"User-Agent": user_agent,
})
try:
with urllib.request.urlopen(api_req) as resp:
data = json.load(resp)
except Exception as err:
return "[INVALID] Failed to fetch releases: " + str(err)
latest = data["info"]["version"]
if latest == current_version:
return "[OK] Already the latest."
return "[OLD] Version is old, latest is " + latest
else:
return "[INVALID] Not supported to get updates for this package."
def get_repo_filename(s):
url = urlparse(s)
if url.scheme == "github":
ghname = f"{url.hostname}-{url.path.replace('/', '')}"
return f"github-{ghname}-{url.fragment}.tar.zst"
elif url.scheme == "gitea":
gitea_name = url.path.replace('/', '-')
gitea_host = url.hostname.split('.')[-2]
return f"{gitea_host}{gitea_name}-{url.fragment}.tar.zst"
elif url.scheme == "gitlab":
gitlab_name = url.path.replace('/', '-')
gitlab_host = url.hostname.split('.')[-2]
return f"{gitlab_host}{gitlab_name}-{url.fragment}.tar.zst"
elif url.scheme == "srht":
srht_name = url.path.replace('~', '').replace('/', '-')
srht_host = url.hostname.split('.')[-2]
return f"{srht_host}{srht_name}-{url.fragment}.tar.zst"
elif url.scheme == "pypi":
return f"pypi-{url.hostname}-{url.fragment}.tar.zst"
else:
raise RuntimeError(f"Unsupported scheme \"{url.scheme}\"")
def get_repo_url(s):
repo_url = os.environ.get("SEMIOS_SOURCE_REPO", DEFAULT_REPO)
return f"{repo_url}/{get_repo_filename(s)}"
def create_srcpkg(s, postprocess="") -> str:
origin_url = get_origin_url(s)
origin_dir = sources.download_decompress(origin_url)
os.chdir(origin_dir)
for program in postprocess.split(','):
program = program.strip()
if program == "":
continue
elif program == "rust":
postprocess_rust()
elif program == "autotools":
postprocess_autotools()
elif program == "go":
postprocess_go()
else:
raise RuntimeError(f"Unknown postprocessor \"{program}\"")
subprocess.run(["tar", "cpf", "../srcpkg.tar", "--numeric-owner", "."], check=True)
os.chdir("../")
subprocess.run(["zstd", "-q", "-f", "-o", get_repo_filename(s), "srcpkg.tar"], check=True)
return os.getcwd() + "/" + get_repo_filename(s)