Merge pull request 'feat: pretty output for build scripts' (#121) from sisungo/ports:pretty-output into main

Reviewed-on: #121
This commit is contained in:
sisungo committed 2026-10-29 20:28:54 +08:00
commit bc253ce53d
9 files changed
+236 -84

No files matched your search

+1 -1
View File
@@ -1 +1 @@
from . import arch, atombuild, make, packie, pkgcomposer, sources, managed_source
from . import arch, atombuild, make, packie, pkgcomposer, sources, managed_source, logging
+4 -3
View File
@@ -102,7 +102,7 @@ def prepare_build_env(root: str, extreq: list[str] = []):
def enter_build_env(root: str, cmd: list[str], chdir: str = "/"):
reserve_env = ["https_proxy", "http_proxy", "all_proxy", "SEMIOS_SOURCE_REPO"]
reserve_env = ["https_proxy", "http_proxy", "all_proxy", "SEMIOS_SOURCE_REPO", "TERM"]
reserve_env_args = []
for i in reserve_env:
if os.environ.get(i):
@@ -124,8 +124,9 @@ def enter_build_env(root: str, cmd: list[str], chdir: str = "/"):
"--setenv", "SEMIOS_PKGBUILD_IN_ATOMIC", "1",
"--setenv", "USER", "root",
"--setenv", "LOGNAME", "root",
"--chdir",
chdir,
"--setenv", "LANG", "C.UTF-8",
"--setenv", "LC_ALL", "C.UTF-8",
"--chdir", chdir,
]
+ reserve_env_args
+ cmd,
+61 -29
View File
@@ -1,4 +1,5 @@
import os
import shlex
import shutil
import subprocess
@@ -6,28 +7,22 @@ from lib.common import treedir
from . import make as libmake
from . import pkgcomposer
from . import logging
def configure(rem: list[str] = []):
subprocess.run(["./configure"] + rem, check=True)
# Common helpers
def write_prev_configure(args: list[str]):
with open("_cpp_configure", "w", encoding="utf-8") as file:
file.write(shlex.join(args) + "\n")
def cmake(rem: list[str] = []):
source_dir = os.getcwd()
os.makedirs("../cmake_build", exist_ok=True)
os.chdir("../cmake_build")
subprocess.run(
[
"cmake",
"-GNinja",
"-DCMAKE_BUILD_TYPE=Release",
"-DCMAKE_INSTALL_PREFIX=/",
source_dir,
]
+ rem,
check=True,
)
def read_prev_configure() -> list[str] | None:
try:
with open("_cpp_configure", "r", encoding="utf-8") as file:
return shlex.split(file.read())
except FileNotFoundError:
return None
def _move_install():
subprocess.run(["sh", "-c", "cp -r ./pkg/*/* . 2>/dev/null || true"], check=False)
@@ -35,55 +30,92 @@ def _move_install():
["sh", "-c", "cp -r ./usr/local/* . 2>/dev/null || true"], check=False
)
subprocess.run(["sh", "-c", "cp -r ./usr/* . 2>/dev/null || true"], check=False)
subprocess.run(["rm", "-rf", "./pkg", "./usr"], check=False)
subprocess.run(["rm", "-rf", "./pkg", "./usr", "./local"], check=False)
# AutoTools & GNU Make
def configure(rem: list[str] = []):
if read_prev_configure() == rem:
logging.step("Skipping previously completed configuration.")
else:
logging.step("Configuring project via AutoTools...")
logging.run_volatile(["./configure"] + rem, check=True)
write_prev_configure(rem)
def make(rem: list[str] = []):
subprocess.run(["make", f"-j{os.cpu_count()}"] + rem, check=True)
logging.step("Building project via Unix Makefile...")
logging.run_volatile(["make", f"-j{os.cpu_count()}"] + rem, check=True)
def make_install(rem: list[str] | None = None, chdir: bool = True, move: bool = True):
logging.step("Installing project to temporary directory via Unix Makefile...")
default_rem = ["DESTDIR=" + os.getcwd() + "/../cpp_install"]
if rem is None:
try:
shutil.rmtree("../cpp_install")
except:
pass
subprocess.run(["make", "install"] + (rem or default_rem), check=True)
logging.run_volatile(["make", "install"] + (rem or default_rem), check=True)
if chdir:
os.chdir("../cpp_install")
if chdir and move:
_move_install()
# CMake
def cmake(rem: list[str] = []):
source_dir = os.getcwd()
os.makedirs("../cmake_build", exist_ok=True)
os.chdir("../cmake_build")
if read_prev_configure() == rem:
logging.step("Skipping previously completed configuration.")
else:
logging.step("Configuring project via CMake...")
logging.run_volatile(
["cmake", "-GNinja", "-DCMAKE_BUILD_TYPE=Release", "-DCMAKE_INSTALL_PREFIX=/", source_dir] + rem,
check=True,
)
write_prev_configure(rem)
# Ninja
def ninja(rem: list[str] = []):
subprocess.run(["ninja"] + rem, check=True)
logging.step("Building project via Ninja...")
logging.run_volatile(["ninja"] + rem, check=True)
def ninja_install(rem: list[str] = [], chdir: bool = True, move: bool = True):
logging.step("Installing project to temporary directory via Ninja...")
if chdir:
os.environ["DESTDIR"] = os.getcwd() + "/../cpp_install"
subprocess.run(["ninja", "install"] + rem, check=True)
logging.run_volatile(["ninja", "install"] + rem, check=True)
if chdir:
os.chdir(os.environ["DESTDIR"])
if chdir and move:
_move_install()
# Meson
def meson_setup(rem: list[str] = []):
subprocess.run(["meson", "setup", "_meson_build"] + rem + ["--buildtype=release"], check=True)
if read_prev_configure() == rem:
logging.step("Skipping previously completed configuration.")
else:
logging.step("Configuring project via Meson...")
logging.run_volatile(["meson", "setup", "../_meson_build"] + rem + ["--buildtype=release"], check=True)
write_prev_configure(rem)
os.chdir("../_meson_build")
def meson_compile(rem: list[str] = []):
subprocess.run(["meson", "compile", "-C", "_meson_build"] + rem, check=True)
logging.step("Building project via Meson...")
logging.run_volatile(["meson", "compile"] + rem, check=True)
def meson_install(rem: list[str] | None = None, chdir: bool = True, move: bool = True):
logging.step("Install project to temporary directory via Meson...")
default_rem = ["--destdir", f"{os.getcwd()}/../cpp_install"]
if not rem:
os.makedirs("../cpp_install", exist_ok=True)
subprocess.run(
["meson", "install", "-C", "_meson_build"] + (rem or default_rem), check=True
logging.run_volatile(
["meson", "install"] + (rem or default_rem), check=True
)
if chdir:
os.chdir("../cpp_install")
+114
View File
@@ -0,0 +1,114 @@
import os
import re
import shutil
import subprocess
import sys
import unicodedata
_ANSI_RE = re.compile(r"\033\[[0-9;?]*[ -/]*[@-~]")
_volatile_pending = False
def _char_width(ch: str) -> int:
if unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Me", "Cf"):
return 0
return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
def _display_width(s: str) -> int:
return sum(_char_width(ch) for ch in _ANSI_RE.sub("", s))
def _truncate(s: str, cols: int, ellipsis: str = "…") -> str:
if cols <= 0 or _display_width(s) <= cols:
return s
budget = max(0, cols - _display_width(ellipsis))
out = []
width = 0
i = 0
while i < len(s):
m = _ANSI_RE.match(s, i)
if m:
out.append(m.group())
i = m.end()
continue
ch = s[i]
i += 1
w = _char_width(ch)
if width + w > budget:
break
out.append(ch)
width += w
return "".join(out) + ellipsis + "\033[0m"
def _terminal_columns() -> int:
try:
return os.get_terminal_size(sys.stderr.fileno()).columns or 80
except (OSError, ValueError, AttributeError):
return shutil.get_terminal_size((80, 24)).columns or 80
def _fit_single_line(s: str) -> str:
if not sys.stderr.isatty():
return s
return _truncate(s, max(1, _terminal_columns() - 1))
def _finish_volatile():
global _volatile_pending
if _volatile_pending:
sys.stderr.write("\n")
sys.stderr.flush()
_volatile_pending = False
def step(s: str):
_finish_volatile()
print(f"=> \033[34m{s}\033[0m", file=sys.stderr)
def volatile(s: str):
global _volatile_pending
sys.stderr.write(f"\r\033[K{s}")
sys.stderr.flush()
_volatile_pending = True
def warning(s: str):
_finish_volatile()
print(f"\033[33mwarning: {s}\033[0m", file=sys.stderr)
def error(s: str):
_finish_volatile()
print(f"\033[31merror: {s}\033[0m", file=sys.stderr)
def run_volatile(cmd, *, check=False, **kwargs):
kwargs.setdefault("stdout", subprocess.PIPE)
kwargs.setdefault("stderr", subprocess.STDOUT)
kwargs.setdefault("text", True)
kwargs.setdefault("bufsize", 1)
lines = []
proc = subprocess.Popen(cmd, **kwargs)
try:
if proc.stdout is not None:
for line in proc.stdout:
line = line.rstrip("\r\n")
lines.append(line)
volatile(_fit_single_line(f"\033[2m ~ {line}\033[0m"))
returncode = proc.wait()
finally:
_finish_volatile()
if check and returncode != 0:
error(f"process exited with code {returncode}")
if lines:
sys.stderr.write("\n".join(lines) + "\n")
sys.stderr.flush()
raise subprocess.CalledProcessError(returncode, cmd)
return returncode
+4 -3
View File
@@ -2,9 +2,7 @@ import typing
import hashlib
import os
from lib import arch
from . import pkgcomposer, sources, managed_source
from . import pkgcomposer, sources, managed_source, logging, arch
_key_global = "@global"
_key_version = "version"
@@ -164,11 +162,13 @@ def block_hook(hook: str):
def source_url(url: str):
if not _dry_run:
logging.step(f"Downloading project source code from \"{url}\"...")
sources.source_url(url)
def source_git(url: str, branch: str | None = None):
if not _dry_run:
logging.step(f"Cloning project source code from \"{url}\" (branch \"{branch}\")...")
sources.source_git(url, branch)
@@ -177,6 +177,7 @@ def source_managed(s: str, postprocess: str = ""):
_managed_source_url = s
_managed_source_postprocess = postprocess
if not _dry_run:
logging.step(f"Downloading project source code from \"{s}\"...")
sources.source_url(managed_source.get_repo_url(s))
+1 -2
View File
@@ -2,7 +2,6 @@ import json
import os
import shutil
import subprocess
import sys
class PkgComposer:
@@ -44,7 +43,7 @@ class PkgComposer:
],
check=True,
)
subprocess.run(["zstd", "--rm", "-f", f"{self.pkgfile}.tar", "-o", self.pkgfile], check=True)
subprocess.run(["zstd", "--rm", "-fq", f"{self.pkgfile}.tar", "-o", self.pkgfile], check=True)
def makedir(self, name: str):
os.mkdir(f"{self.workdir}/bundle/{name}")
+5 -11
View File
@@ -1,7 +1,7 @@
import os
import subprocess
from . import arch, make, pkgcomposer
from . import arch, make, pkgcomposer, logging
def _rust_triple(semios: str) -> str:
@@ -9,6 +9,7 @@ def _rust_triple(semios: str) -> str:
def build(rem: list[str] = []):
logging.step("Building project via Cargo...")
cmdline = [
"cargo",
"build",
@@ -19,7 +20,7 @@ def build(rem: list[str] = []):
os.environ["RUSTFLAGS"] = (
os.environ.get("RUSTFLAGS", "") + " -C target-feature=-crt-static"
)
subprocess.run(cmdline)
logging.run_volatile(cmdline, check=True)
def artifacts_dir():
@@ -33,19 +34,12 @@ def _do_auto_pack(pc: pkgcomposer.PkgComposer, srcdir: str, dstdir: str, filter)
if filter(ent):
if ent.is_dir(follow_symlinks=False):
pc.makedir(f"{dstdir}/{ent.name}")
elif ent.is_file(follow_symlinks=False):
pc.addfile(ent.path, f"{dstdir}/{ent.name}")
elif ent.is_symlink() and not os.path.isabs(os.readlink(ent.path)):
elif ent.is_file(follow_symlinks=False) or (ent.is_symlink() and not os.path.isabs(os.readlink(ent.path))):
pc.addfile(ent.path, f"{dstdir}/{ent.name}")
def _autopack_filter_lib(ent) -> bool:
if ent.is_dir(follow_symlinks=False):
return False
if ent.name.endswith(".so"):
return True
else:
return False
return ent.name.endswith(".so") and ent.is_file(follow_symlinks=False)
def _autopack_filter_bin(ent) -> bool:
-2
View File
@@ -1,9 +1,7 @@
import os
import subprocess
import sys
import tarfile
import urllib.parse
import urllib.request
import zipfile
+46 -33
View File
@@ -60,7 +60,7 @@ def load_pkgbuild(pkgname):
def run_hooks(map, arg: typing.Any = None):
current_dir = os.getcwd()
for n in map.keys():
for n in map:
if n in lib.make._blocked_hooks:
continue
if arg:
@@ -84,7 +84,7 @@ def cmd_build_package(package: str):
# Check architecture support
if not lib.make._supported_arch(lib.arch.get_target()):
print(f"Architecture {lib.arch.get_target()} is not supported for this package")
lib.logging.error(f"Architecture {lib.arch.get_target()} is not supported for this package.")
exit(1)
# Run `pre_build` hooks
@@ -95,17 +95,20 @@ def cmd_build_package(package: str):
os.chdir(lib.sources.sources_dir_name())
lib.make._on_build()
else:
print("on_build(): Not defined")
lib.logging.error("The pkgbuild file has specified no build function.")
exit(1)
# Run `post_build` hooks
run_hooks(hooks.post_build)
# Pack packages
for pkgname in lib.make._pkginfo.keys():
for pkgname in lib.make._pkginfo:
lib.make._current_pkgname = pkgname
if pkgname == lib.make._key_global:
continue
else:
lib.logging.step(f"Packing package \"{pkgname}\"...")
pkginfo = lib.make._pkginfo[pkgname]
pkgver = pkginfo[lib.make._key_version]
@@ -209,13 +212,17 @@ def cmd_build_atom(pkgname: str):
load_pkgbuild(pkgname)
# Initialize build environment
lib.logging.step("Preparing environment for Atom Build...")
lib.atombuild.prepare_build_env(build_env_root, lib.make._builddep)
lib.atombuild.copy_pkgbuild_tree(repo_root, pkgname, build_env_root)
lib.atombuild.enter_build_env(
build_env_root,
["./x", "--target", lib.arch.get_target(), "build", pkgname],
chdir="/Atom",
)
try:
lib.atombuild.enter_build_env(
build_env_root,
["./x", "--target", lib.arch.get_target(), "build", pkgname],
chdir="/Atom",
)
except:
exit(1)
# Copy artifacts
atom_target_dir = f"{build_env_root}/Atom/packages/{pkgname}/target"
@@ -223,7 +230,7 @@ def cmd_build_atom(pkgname: str):
for i in os.listdir(atom_target_dir):
if i.endswith(".pkg"):
shutil.copy2(f"{atom_target_dir}/{i}", f"{target_dir}/{i}")
except Exception:
except:
pass
# Build success
@@ -272,27 +279,33 @@ def cmd_check_updates(pkgname):
exit(1)
print(lib.managed_source.get_updates(lib.make._managed_source_url))
def main():
if args.subcommand == "build":
if args.atombuild:
cmd_build_atom(args.BUILD_PKGNAME)
else:
cmd_build_package(args.BUILD_PKGNAME)
elif args.subcommand == "clean":
if args.all:
pkgs = os.listdir("packages")
else:
pkgs = args.CLEAN_PKGNAME
cmd_clean_package(pkgs)
elif args.subcommand == "list":
cmd_list(args.ITEM)
elif args.subcommand == "repo-push":
cmd_repo_push(args.REPO_DIR, args.REPO_PUSH_PKGNAME)
elif args.subcommand == "source":
if args.vendor:
cmd_vendor_src(args.vendor, args.PKGNAME)
if args.check_updates:
cmd_check_updates(args.PKGNAME)
else:
print("error: no action specified", file=sys.stderr)
exit(1)
if args.subcommand == "build":
if args.atombuild:
cmd_build_atom(args.BUILD_PKGNAME)
else:
cmd_build_package(args.BUILD_PKGNAME)
elif args.subcommand == "clean":
if args.all:
pkgs = os.listdir("packages")
else:
pkgs = args.CLEAN_PKGNAME
cmd_clean_package(pkgs)
elif args.subcommand == "list":
cmd_list(args.ITEM)
elif args.subcommand == "repo-push":
cmd_repo_push(args.REPO_DIR, args.REPO_PUSH_PKGNAME)
elif args.subcommand == "source":
if args.vendor:
cmd_vendor_src(args.vendor, args.PKGNAME)
if args.check_updates:
cmd_check_updates(args.PKGNAME)
else:
print("error: no action specified", file=sys.stderr)
exit(1)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
exit(1)