Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-24 12:16:35 -05:00
commit 1e0150c773
24 files changed
+4796

No files matched your search

+478
View File
@@ -0,0 +1,478 @@
#! @file package.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `package`: the project installed into its stage, then written as
#! each package asked for into its output folder's `dist`. tar and zip files
#! hold the stage under a folder of the project's name, version, and target;
#! Debian and Arch packages hold it under the prefix they install to, `/usr`
#! unless given; and an rpm package is built by `rpmbuild` from a spec written
#! for it. Every entry is dated `SOURCE_DATE_EPOCH`, where it's set, so a
#! package is written alike each time.
import std;
import std::io;
import std::process;
import std::time;
import system;
import blossom::models;
import blossom::management;
module blossom::pipeline;
#! The packages blossom writes.
pub val formats: strview[5] = ["tar", "zip", "deb", "arch", "rpm"];
#! Builds the project, installs it into its stage, then writes its packages.
#! @param this The session.
#! @param asked The formats asked for, each a format or several with `,`
#! between them, or none for `tar`, or `zip` for Windows.
#! @param prefix Where a Debian, Arch, or rpm package installs, or empty for
#! `/usr`.
#! @returns The status the command ends with.
pub def session::package_command(&mut this, asked: span<strview>, prefix: strview): i32 {
var chosen := vector::<strview>::new();
for &each in asked {
for format in each.split(',') {
continue if format.length == 0;
var known := false;
for &name in formats {
known = known || name == format;
}
if !known {
fatal(2, $"`{format}` is no format: write `tar`, `zip`, `deb`, `arch`, or `rpm`.".view());
}
chosen.append(format);
}
}
val platform := this.package_platform();
if chosen.length == 0 {
chosen.append(platform == "windows-x86_64" ? "zip" : "tar");
}
var installed_at: strview = "/usr";
if prefix.length != 0 {
installed_at = prefix;
}
# What a system's package can't hold is said before anything's built.
for &format in chosen {
if format == "deb" || format == "arch" || format == "rpm" {
_ = distro_arch(platform, format, "");
_ = distro_name(&this.space.projects[0]);
_ = distro_version(&this.space.projects[0]);
}
}
this.build(false, "");
return 1 if this.failed;
val holder := &this.space.projects[0];
val output := holder.output;
val stage := output.join("stage");
val dist := output.join("dist");
if management::remove_tree(&stage) is error(why) {
fatal(1, $"`{stage.view()}` can't be emptied: {why}.".view());
}
_ = io::create_directories(&stage);
if this.install(&stage) == 0 {
fatal(1, $"{holder.identity.view()} installs nothing, so there's nothing to package.".view());
}
_ = io::create_directories(&dist);
val mtime := build_time();
for &format in chosen {
var made := path::new();
if format == "tar" || format == "zip" {
made = this.archive(format, &stage, &dist, platform, mtime);
} else if format == "deb" {
made = this.debian(&stage, &dist, trimmed(installed_at), platform, mtime);
} else if format == "arch" {
made = this.arch_package(&stage, &dist, trimmed(installed_at), platform, mtime);
} else {
made = this.rpm(&stage, &dist, trimmed(installed_at), platform);
}
io::println($"Packaged {made.view()}".view());
}
return 0;
}
# What the packages are for: what `--target` says, else what the first program
# that says is built for, else the system blossom runs on.
def session::package_platform(&this): strview {
if this.space.platform.length != 0 {
return this.space.platform.view();
}
for &each in this.space.projects[0].targets {
if each.kind == models::target_kind::program && each.system.length != 0 {
return each.system.view();
}
}
when os == windows {
return "windows-x86_64";
}
return "linux-x86_64";
}
# Writes a tar archive, compressed by `gzip`, or a zip file, of the stage under
# a folder of the project's name, version, and target.
def session::archive(&mut this, format: strview, stage: &path, dist: &path, platform: strview, mtime: i64): path {
val holder := &this.space.projects[0];
val stem := $"{holder.name.view()}-{holder.semv.view()}-{platform}";
val items := staged(stage, stem.view());
if format == "zip" {
var made := zip { bytes = string::new(nothing {}), central = string::new(nothing {}), mtime = mtime };
for &item in items {
if item.folder {
made.folder(item.name.view());
} else {
val data := read_all(&item.source);
made.file(item.name.view(), data.view(), item.mode);
}
}
val at := dist.join($"{stem.view()}.zip".view());
write_whole(&at, made.finish());
return at;
}
var made := tar { bytes = string::new(nothing {}), mtime = mtime };
add_items(&mut made, items.view(), strview::empty());
val at := dist.join($"{stem.view()}.tar".view());
write_whole(&at, made.finish());
return this.compressed(&at, "gzip", ".gz");
}
# Writes a Debian package: its control file and the digest of each file in a
# tar compressed by `gzip`, and the stage under the prefix in one compressed by
# `xz`, as members of an `ar` archive.
def session::debian(&mut this, stage: &path, dist: &path, prefix: strview, platform: strview, mtime: i64): path {
val holder := &this.space.projects[0];
val name := distro_name(holder);
val version := distro_version(holder);
val arch := distro_arch(platform, "deb", "amd64");
val items := staged(stage, prefix);
var sums := string::new(nothing {});
var size := 0u;
for &item in items {
continue if item.folder;
val data := read_all(&item.source);
size += data.length;
sums.append($"{md5(data.view()).view()} {item.name.view()}\n".view());
}
var control := string::new(nothing {});
control.append($"Package: {name.view()}\n".view());
control.append($"Version: {version.view()}-1\n".view());
control.append($"Architecture: {arch}\n".view());
control.append($"Maintainer: {or_else(holder.package.auth.view(), "Unknown <unknown@localhost>")}\n".view());
control.append($"Installed-Size: {(size + 1023) / 1024}\n".view());
control.append("Section: misc\nPriority: optional\n");
if holder.package.url.length != 0 {
control.append($"Homepage: {holder.package.url.view()}\n".view());
}
control.append($"Description: {or_else(holder.package.desc.view(), holder.name.view())}\n".view());
val work := dist.join("deb");
_ = management::remove_tree(&work);
_ = io::create_directories(&work);
var controls := tar { bytes = string::new(nothing {}), mtime = mtime };
controls.folder(".");
controls.file("./control", control.view(), 0o644);
controls.file("./md5sums", sums.view(), 0o644);
val control_at := work.join("control.tar");
write_whole(&control_at, controls.finish());
val control_gz := this.compressed(&control_at, "gzip", ".gz");
var data := tar { bytes = string::new(nothing {}), mtime = mtime };
data.folder(".");
add_items(&mut data, items.view(), "./");
val data_at := work.join("data.tar");
write_whole(&data_at, data.finish());
val data_xz := this.compressed(&data_at, "xz", ".xz");
var made := ar::new(mtime);
made.member("debian-binary", "2.0\n");
made.member("control.tar.gz", read_all(&control_gz).view());
made.member("data.tar.xz", read_all(&data_xz).view());
val at := dist.join($"{name.view()}_{version.view()}-1_{arch}.deb".view());
write_whole(&at, made.bytes.view());
_ = management::remove_tree(&work);
return at;
}
# Writes an Arch package: its `.PKGINFO`, its `.MTREE` of each entry's
# digests, compressed by `gzip`, and the stage under the prefix, in a tar
# compressed by `zstd`.
def session::arch_package(&mut this, stage: &path, dist: &path, prefix: strview, platform: strview, mtime: i64): path {
val holder := &this.space.projects[0];
val name := distro_name(holder);
val version := distro_version(holder);
val arch := distro_arch(platform, "arch", "x86_64");
val items := staged(stage, prefix);
var size := 0u;
for &item in items {
continue if item.folder;
val found := io::info(&item.source) else (_) { continue; };
size += found.size;
}
var info := string::from("# Generated by blossom\n", nothing {});
info.append($"pkgname = {name.view()}\npkgbase = {name.view()}\nxdata = pkgtype=pkg\n".view());
info.append($"pkgver = {version.view()}-1\n".view());
info.append($"pkgdesc = {or_else(holder.package.desc.view(), holder.name.view())}\n".view());
if holder.package.url.length != 0 {
info.append($"url = {holder.package.url.view()}\n".view());
}
info.append($"builddate = {mtime}\n".view());
info.append($"packager = {or_else(holder.package.auth.view(), "Unknown Packager")}\n".view());
info.append($"size = {size}\narch = {arch}\n".view());
if holder.package.lic.length != 0 {
info.append($"license = {holder.package.lic.view()}\n".view());
}
var tree := string::from("#mtree\n/set type=file uid=0 gid=0 mode=644\n", nothing {});
tree.append($"./.PKGINFO time={mtime}.0 size={info.length} md5digest={md5(info.view()).view()} sha256digest={sha256(info.view()).view()}\n".view());
for &item in items {
val named := mtree_escaped(item.name.view());
if item.folder {
tree.append($"./{named.view()} time={mtime}.0 mode=755 type=dir\n".view());
continue;
}
val data := read_all(&item.source);
var mode := string::new(nothing {});
if item.mode != 0o644 {
mode.append(" mode=");
mode.append(octal_text(item.mode).view());
}
tree.append($"./{named.view()} time={mtime}.0{mode.view()} size={data.length} md5digest={md5(data.view()).view()} sha256digest={sha256(data.view()).view()}\n".view());
}
val work := dist.join("arch");
_ = management::remove_tree(&work);
_ = io::create_directories(&work);
val tree_at := work.join("mtree");
write_whole(&tree_at, tree.view());
val tree_gz := this.compressed(&tree_at, "gzip", ".gz");
var made := tar { bytes = string::new(nothing {}), mtime = mtime };
made.file(".PKGINFO", info.view(), 0o644);
made.file(".MTREE", read_all(&tree_gz).view(), 0o644);
add_items(&mut made, items.view(), strview::empty());
val at := dist.join($"{name.view()}-{version.view()}-1-{arch}.pkg.tar".view());
write_whole(&at, made.finish());
_ = management::remove_tree(&work);
return this.compressed(&at, "zstd", ".zst");
}
# Builds an rpm package with `rpmbuild`, from a spec written for it that copies
# the stage under the prefix.
def session::rpm(&mut this, stage: &path, dist: &path, prefix: strview, platform: strview): path {
val holder := &this.space.projects[0];
val name := distro_name(holder);
val version := distro_version(holder);
val arch := distro_arch(platform, "rpm", "x86_64");
val summary := or_else(holder.package.desc.view(), holder.name.view());
var spec := string::from("%define debug_package %{nil}\n", nothing {});
spec.append($"Name: {name.view()}\nVersion: {version.view()}\nRelease: 1\nSummary: {summary}\n".view());
spec.append($"License: {or_else(holder.package.lic.view(), "Unspecified")}\n".view());
if holder.package.url.length != 0 {
spec.append($"URL: {holder.package.url.view()}\n".view());
}
spec.append($"BuildArch: {arch}\n\n%description\n{summary}\n\n%install\n".view());
spec.append("mkdir -p \"%{buildroot}/");
spec.append(prefix);
spec.append("\"\ncp -a \"");
spec.append(stage.view());
spec.append("/.\" \"%{buildroot}/");
spec.append(prefix);
spec.append("/\"\n\n%files\n%defattr(-,root,root,-)\n");
val items := staged(stage, prefix);
for &item in items {
continue if item.folder;
spec.append($"\"/{item.name.view()}\"\n".view());
}
val top := dist.join("rpmbuild");
val file := top.join("SPECS").join($"{name.view()}.spec".view());
if !written(&file, spec.view()) {
fatal(1, $"`{file.view()}` can't be written.".view());
}
var words := vector::<string>::new();
words.append(string::from("rpmbuild", nothing {}));
words.append(string::from("-bb", nothing {}));
words.append(string::from("--define", nothing {}));
words.append($"_topdir {top.view()}");
words.append(string::from(file.view(), nothing {}));
var building := this.command(words.view(), dist);
val status := building.run() else (_) {
fatal(1, $"rpm packages need `rpmbuild`, which isn't found; the spec is written to `{file.view()}`.".view());
return path::new();
};
if !status.succeeded {
fatal(1, "`rpmbuild` failed.");
}
# `rpmbuild` puts the package in a folder of its architecture.
val built := top.join("RPMS").join(arch).join($"{name.view()}-{version.view()}-1.{arch}.rpm".view());
val at := dist.join($"{name.view()}-{version.view()}-1.{arch}.rpm".view());
if io::rename(&built, &at) is error(why) {
fatal(1, $"`{built.view()}` can't be moved to `{at.view()}`: {why}.".view());
}
return at;
}
# Adds entries to a tar archive, each name after a prefix, as `./`.
def add_items(made: &mut tar, items: span<entry>, before: strview): void {
for &item in items {
val name := $"{before}{item.name.view()}";
if item.folder {
made.folder(name.view());
} else {
val data := read_all(&item.source);
made.file(name.view(), data.view(), item.mode);
}
}
}
# Compresses a file with a program of the system, `gzip`, `xz`, or `zstd`,
# which replaces it with one named with a suffix, as `.gz`, giving its path.
def session::compressed(&mut this, at: &path, program: strview, suffix: strview): path {
var words := vector::<string>::new();
words.append(string::from(program, nothing {}));
if program == "gzip" {
words.append(string::from("-n", nothing {}));
words.append(string::from("-9", nothing {}));
} else if program == "zstd" {
words.append(string::from("-q", nothing {}));
words.append(string::from("--rm", nothing {}));
words.append(string::from("-19", nothing {}));
}
words.append(string::from("-f", nothing {}));
words.append(string::from(at.view(), nothing {}));
val folder := at.parent() else { return path::new(); };
var compressing := this.command(words.view(), &folder);
val status := compressing.run() else (why) {
fatal(1, $"`{program}` can't be run, to compress `{at.view()}`: {why}.".view());
return path::new();
};
if !status.succeeded {
fatal(1, $"`{program}` failed to compress `{at.view()}`.".view());
}
return path::parse($"{at.view()}{suffix}".view()) else (_) { return path::new(); };
}
# When a package's entries were written: `SOURCE_DATE_EPOCH`, where it's set,
# else now.
def build_time(): i64 {
if process::variable("SOURCE_DATE_EPOCH") is some(given) {
if integer::parse::<i64>(given) is value(seconds) {
return seconds;
}
}
return time::timestamp::now().unix;
}
# The project's name as a system's package names it: in lower case, with `-`
# for `_`, two or more letters, digits, `.`, `+`, or `-`, starting with a
# letter or digit.
def distro_name(holder: &models::project): string {
var made := holder.name.lower();
for k in 0..made.length {
if made[k] == '_' {
made[k] = '-';
}
}
var fits := made.length >= 2 && made[0].is_alnum;
for k in 0..made.length {
val byte := made[k];
fits = fits && (byte.is_alnum || byte == '.' || byte == '+' || byte == '-');
}
if !fits {
fatal(2, $"`{holder.name.view()}` can't name a system's package: it needs two or more letters, digits, `.`, `+`, or `-`.".view());
}
return made;
}
# The project's version as a system's package takes it: starting with a digit,
# with only letters, digits, `.`, `+`, or `~`.
def distro_version(holder: &models::project): string {
val text := holder.semv.view();
var fits := text.length != 0 && text[0].is_digit;
for k in 0..text.length {
val byte := text[k];
fits = fits && (byte.is_alnum || byte == '.' || byte == '+' || byte == '~');
}
if !fits {
fatal(2, $"{holder.identity.view()}'s version, `{text}`, can't be a system package's: it starts with a digit, and holds only letters, digits, `.`, `+`, or `~`.".view());
}
return string::from(text, nothing {});
}
# The architecture a system's packages name x86-64 by, where they're for Linux.
def distro_arch(platform: strview, format: strview, name: strview): strview {
if platform != "linux-x86_64" {
fatal(2, $"{format} packages are for Linux, not `{platform}`.".view());
}
return name;
}
# A path in `.MTREE`, each byte but letters, digits, and `._/+-` written as `\`
# and three octal digits.
def mtree_escaped(text: strview): string {
var made := string::new(nothing {});
for k in 0..text.length {
val byte := text[k];
if byte.is_alnum || byte == '.' || byte == '_' || byte == '/' || byte == '+' || byte == '-' {
made.push(byte);
} else {
made.push('\\');
made.push('0' + (byte >> 6));
made.push('0' + ((byte >> 3) & 7));
made.push('0' + (byte & 7));
}
}
return made;
}
# A mode in octal, as `755`.
def octal_text(mode: u32): string {
var made := string::new(nothing {});
made.push('0' + ((mode >> 6) & 7) as u8);
made.push('0' + ((mode >> 3) & 7) as u8);
made.push('0' + (mode & 7) as u8);
return made;
}
# Text, or another where it's empty.
def or_else(text: strview, fallback: strview): strview {
return text.length != 0 ? text : fallback;
}
# The whole of a file, stopping the command where it can't be read.
def read_all(at: &path): string {
return io::read_file(at) else (why) {
fatal(1, $"`{at.view()}` can't be read: {why}.".view());
return string::new(nothing {});
};
}
# Writes a file whole, stopping the command where it can't be written.
def write_whole(at: &path, bytes: strview): void {
if !written(at, bytes) {
fatal(1, $"`{at.view()}` can't be written.".view());
}
}
# A prefix as a package holds it: without the `/` it starts or ends with.
def trimmed(text: strview): strview {
var start := 0u;
var end := text.length;
while start < end && text[start] == '/' {
start++;
}
while end > start && text[end - 1] == '/' {
end--;
}
return text.substr(start, end - start);
}