feat: support executable and multi-binary releases
Rust CI Cargo tests passed.
Gitea/rust_realease/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-09-30 16:07:29 +02:00
parent 7a1de6803c
commit 94e29010ad
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
11 changed files with 427 additions and 205 deletions

View File

@ -1,10 +1,10 @@
# rust_realease
`rust_realease` builds and publishes one binary from a Rust package to a Gitea release. Give it a local project directory or a Git URL. It inspects Cargo metadata, checks the version tag, builds the selected targets with Cross, creates `.tgz` archives and `SHA256SUMS`, uploads them, and verifies release downloads. It can also prepare a project for release with explicit commit, tag, and push options.
`rust_realease` builds and publishes the binaries from a Rust package to a Gitea release. Give it a local project directory or a Git URL. It inspects Cargo metadata, checks the version tag, builds the selected targets with Cross, creates cargo-binstall-compatible `.tgz` archives, directly downloadable executables, or both, writes `SHA256SUMS`, uploads the assets, and verifies release downloads. It can also prepare a project for release with explicit commit, tag, and push options.
## Install
Install Rust and Cargo, Git, Cross, Docker or Podman, and cargo-binstall. A working container backend is needed for release builds.
Install Rust and Cargo, Git, Cross, and Docker or Podman. Install cargo-binstall when producing the default `tgz` artifacts and running end-to-end install verification. A working container backend is needed for release builds.
```bash
cargo install --path . --locked
@ -28,7 +28,7 @@ For a workspace, select the exact Cargo package name:
rust_realease ./my-workspace --package my-tool --dry-run
```
Each run handles one package with one binary. A dry run reports the package, version, expected tag, metadata changes, build targets, archive names, prerequisites, and release destination. It writes no project files, builds no binaries, and changes no Git refs or releases. It exits nonzero when it finds requirements that still need attention.
Each run handles one package and all of its Cargo binary targets. A dry run reports the package, version, expected tag, metadata changes, build targets, artifact names, prerequisites, and release destination. It writes no project files, builds no binaries, and changes no Git refs or releases. It exits nonzero when it finds requirements that still need attention.
## Prepare a release
@ -53,13 +53,13 @@ rust_realease ./my-tool --prepare-repo \
The preparation commit uses your configured Git author and signing settings. The tag is annotated and follows your Git tag-signing configuration (`git config tag.gpgsign true` to sign it); an existing tag is never moved. The branch and tag are pushed atomically without force. Use `--cross-image-tag main` only when you want preparation to set Cross images for the selected targets.
## Build local archives
## Build local artifacts
```bash
rust_realease ./my-tool --stop-after package
```
This runs host `cargo check` and `cargo test`, builds the selected targets with Cross, and writes archives plus `SHA256SUMS` into a new `dist/release-*/` directory. It does not contact Gitea. The default targets are:
This runs host `cargo check` and `cargo test`, builds the selected targets with Cross, and writes the configured artifacts plus `SHA256SUMS` into a new `dist/release-*/` directory. It does not contact Gitea. The default targets are:
- `x86_64-unknown-linux-musl`
- `aarch64-unknown-linux-musl`
@ -67,6 +67,13 @@ This runs host `cargo check` and `cargo test`, builds the selected targets with
Override the matrix with repeatable `--target TARGET` options. Use `--stop-after verify` for host checks alone.
Use `--artifact-format binary` when you only want raw executables, or `--artifact-format both` to publish raw executables alongside the default cargo-binstall archives:
```bash
rust_realease ./my-tool --artifact-format binary --stop-after package
rust_realease ./my-tool --artifact-format both
```
## Publish to Gitea
The package version and release tag must agree. For version `0.1.0`, the default tag is `v0.1.0`. Before ordinary publication, the local tag must point to the checkout and the matching remote tag must exist. Publication requires a clean checkout and an HTTPS Gitea destination.

View File

@ -15,7 +15,7 @@ Its public [v0.1.3 release](https://proxy.dandaedre.com/gitea/idle-org/target_te
`SOURCE` can be a local directory, an HTTP(S) Git URL, an SSH URL, or an SCP-style URL such as `git@host:owner/repo.git`. Remote sources are cloned into a managed checkout. Use `--keep-workdir` to retain that checkout and its artifacts; preparation retains remote checkouts automatically. Local sources are never deleted.
Use `--package NAME` to select one workspace member by its exact Cargo package name. Selection uses `cargo metadata` and accepts inherited workspace version and repository values. Library-only packages and members with multiple binaries cannot be released. Checks, tests, and builds are scoped to the selected package.
Use `--package NAME` to select one workspace member by its exact Cargo package name. Selection uses `cargo metadata` and accepts inherited workspace version and repository values. Library-only packages cannot be released. Every binary target declared by the selected package is built and packaged; this includes binaries with `required-features` when those features are enabled by the package's defaults. Checks, tests, and builds are scoped to the selected package.
`--repository-url https://host/owner/repo` selects the release destination when Cargo metadata or Git origin needs an explicit web URL. Materially conflicting origin and release destinations are refused. Repository URLs with embedded credentials are refused.
@ -45,9 +45,11 @@ token-env = "GITEA_TOKEN"
Use `--tag-prefix ""` for an unprefixed tag such as `0.3.1`. `--tag TAG` must match the selected package version and configured prefix. `--unlocked` permits builds without the usual locked dependency resolution; the default uses `--locked`.
`package.format` accepts `"tgz"`, `"binary"`, or `"both"`. The default `"tgz"` produces cargo-binstall archives. `"binary"` produces only directly downloadable executables and does not require or verify cargo-binstall metadata. `"both"` produces both forms. The `--artifact-format` option overrides this setting for an individual run.
## Metadata and preparation
The publisher checks the selected member's repository and cargo-binstall metadata. `--fix-metadata` repairs supported entries in that member's `Cargo.toml` while preserving comments where practical. It does not commit, tag, or push. To preview the full preparation diff, use `--prepare-repo --dry-run`.
The publisher checks the selected member's repository and, when archives are enabled, its cargo-binstall metadata. `--fix-metadata` repairs supported entries in that member's `Cargo.toml` while preserving comments where practical. It does not commit, tag, or push. To preview the full preparation diff, use `--prepare-repo --dry-run`.
The required binstall contract is:
@ -70,15 +72,16 @@ For repositories whose build scripts need a selected Rust toolchain inside Cross
## Artifact contract
Each archive is named `{name}-{target}-v{version}.tgz` and contains exactly one root directory with one binary:
Each archive is named `{name}-{target}-v{version}.tgz` and contains exactly one root directory with every binary declared by the selected package:
```text
my-tool-x86_64-unknown-linux-musl-v0.1.0.tgz
└── my-tool-x86_64-unknown-linux-musl-v0.1.0/
└── my-tool
├── my-tool
└── my-tool-helper
```
Windows archives contain `my-tool.exe`. `SHA256SUMS` lists the final archive checksums. Archive ownership and timestamps are normalized; identical binary bytes and modes produce identical archives. Separate builds can still produce different binaries.
Windows archive members have an `.exe` suffix. Raw assets are target-qualified to remain unambiguous, for example `my-tool-x86_64-unknown-linux-musl-v0.1.0` and `my-tool-x86_64-pc-windows-gnu-v0.1.0.exe`. `SHA256SUMS` lists every generated asset. Archive ownership and timestamps are normalized; identical binary bytes and modes produce identical archives. Separate builds can still produce different binaries.
## Authentication and security

View File

@ -4,6 +4,12 @@ use std::{
path::{Path, PathBuf},
};
#[derive(Debug)]
pub struct TargetOutputs {
pub target: String,
pub binaries: Vec<(String, PathBuf)>,
}
pub fn prerequisites(
root: &Path,
config: &Config,
@ -144,9 +150,10 @@ pub fn cross_arguments(
target_dir.display().to_string(),
"--package".into(),
project.name.clone(),
"--bin".into(),
project.binary.clone(),
]);
for binary in &project.binaries {
args.extend(["--bin".into(), binary.clone()]);
}
args
}
@ -156,7 +163,7 @@ pub fn build(
config: &Config,
engine: &str,
runner: &Runner,
) -> Result<Vec<(String, PathBuf)>, Error> {
) -> Result<Vec<TargetOutputs>, Error> {
let target_base = project.target_directory.join("binstall-publisher");
fs::create_dir_all(&target_base)
.map_err(|e| Error(format!("cannot create {}: {e}", target_base.display())))?;
@ -188,23 +195,30 @@ pub fn build(
let args = cross_arguments(project, config, target, &target_dir);
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
runner.output_with("cross", &borrowed, root, &environment, &[])?;
let binary = target_dir
.join(target)
.join(profile_dir)
.join(policy::binary_filename(&project.binary, target));
let metadata = fs::symlink_metadata(&binary).map_err(|_| {
Error(format!(
"Build did not produce a regular binary: {}",
binary.display()
))
})?;
if !metadata.file_type().is_file() {
return Err(Error(format!(
"Build did not produce a regular binary: {}",
binary.display()
)));
let mut binaries = Vec::new();
for name in &project.binaries {
let binary = target_dir
.join(target)
.join(profile_dir)
.join(policy::binary_filename(name, target));
let metadata = fs::symlink_metadata(&binary).map_err(|_| {
Error(format!(
"Build did not produce a regular binary: {}",
binary.display()
))
})?;
if !metadata.file_type().is_file() {
return Err(Error(format!(
"Build did not produce a regular binary: {}",
binary.display()
)));
}
binaries.push((name.clone(), binary));
}
outputs.push((target.clone(), binary));
outputs.push(TargetOutputs {
target: target.clone(),
binaries,
});
}
Ok(outputs)
}
@ -217,7 +231,7 @@ mod tests {
let project = SelectedPackage {
name: "cli".into(),
version: "0.1.0".into(),
binary: "cli".into(),
binaries: vec!["cli".into(), "helper".into()],
manifest: PathBuf::from("Cargo.toml"),
repository: None,
target_directory: PathBuf::from("target"),
@ -228,6 +242,7 @@ mod tests {
locked: true,
tag_prefix: "v".into(),
token_env: "GITEA_TOKEN".into(),
package_format: crate::config::PackageFormat::Tgz,
};
let args = cross_arguments(
&project,
@ -248,7 +263,9 @@ mod tests {
"--package",
"cli",
"--bin",
"cli"
"cli",
"--bin",
"helper"
]
);
}

View File

@ -1,6 +1,6 @@
use crate::{
build,
config::{self, Overrides},
config::{self, Overrides, PackageFormat},
error::Error,
gitea::Gitea,
manifest,
@ -65,6 +65,9 @@ pub struct Cli {
pub repository_url: Option<String>,
#[arg(long)]
pub config: Option<PathBuf>,
/// Release tgz archives, raw binaries, or both.
#[arg(long, value_enum)]
pub artifact_format: Option<PackageFormat>,
}
pub fn run(args: Cli) -> Result<(), Error> {
@ -88,6 +91,7 @@ pub fn run(args: Cli) -> Result<(), Error> {
profile: args.profile,
unlocked: args.unlocked,
tag_prefix: args.tag_prefix,
package_format: args.artifact_format,
},
)?;
let runner = Runner::new(&config.token_env).with_verbose(args.verbose);
@ -120,7 +124,7 @@ pub fn run(args: Cli) -> Result<(), Error> {
}
println!("Package: {}", selected.name);
println!("Version: {}", selected.version);
println!("Binary: {}", selected.binary);
println!("Binaries: {}", selected.binaries.join(", "));
println!("Manifest: {}", selected.manifest.display());
println!("Tag: {tag}");
if args
@ -164,9 +168,18 @@ pub fn run(args: Cli) -> Result<(), Error> {
}
}
}
let issues = manifest::changes(&selected.manifest, &repository, &config.tag_prefix)?;
let issues = manifest::changes(
&selected.manifest,
&repository,
&config.tag_prefix,
config.package_format.archives(),
)?;
if issues.is_empty() {
println!("Binstall metadata: valid");
if config.package_format.archives() {
println!("Binstall metadata: valid");
} else {
println!("Release metadata: valid");
}
}
for issue in &issues {
let actual = if issue.actual.is_some() {
@ -206,18 +219,36 @@ pub fn run(args: Cli) -> Result<(), Error> {
return Ok(());
}
for target in &config.targets {
println!(
"{target}: {} ({})",
policy::archive_name(&selected.name, target, &selected.version),
policy::binary_filename(&selected.binary, target)
);
if config.package_format.archives() {
println!(
"{target} archive: {} ({})",
policy::archive_name(&selected.name, target, &selected.version),
selected
.binaries
.iter()
.map(|binary| policy::binary_filename(binary, target))
.collect::<Vec<_>>()
.join(", ")
);
}
if config.package_format.binaries() {
for binary in &selected.binaries {
println!(
"{target} binary: {}",
policy::binary_asset_name(binary, target, &selected.version)
);
}
}
}
for (key, value) in policy::binstall_metadata(&config.tag_prefix) {
println!("Binstall {key}: {value}");
if config.package_format.archives() {
for (key, value) in policy::binstall_metadata(&config.tag_prefix) {
println!("Binstall {key}: {value}");
}
}
println!("Release destination: {repository}/releases/tag/{tag}");
let needs_cross = args.stop_after != Some(Stage::Verify);
let needs_binstall = !args.skip_binstall_test
let needs_binstall = config.package_format.archives()
&& !args.skip_binstall_test
&& args
.stop_after
.is_none_or(|stage| stage.order() >= Stage::Binstall.order());
@ -274,8 +305,8 @@ pub fn run(args: Cli) -> Result<(), Error> {
&checkout.root,
&selected.name,
&selected.version,
&selected.binary,
&outputs,
config.package_format,
)?;
println!(
"Artifacts: {}",
@ -285,10 +316,7 @@ pub fn run(args: Cli) -> Result<(), Error> {
)
);
for artifact in &artifacts {
println!(
"Packaged {}: {}/{}",
artifact.target, artifact.root, artifact.binary
);
println!("Packaged {}: {}", artifact.target, artifact.path.display());
}
if args.stop_after == Some(Stage::Package) {
return Ok(());
@ -321,7 +349,7 @@ pub fn run(args: Cli) -> Result<(), Error> {
None
},
)?;
if !args.skip_binstall_test {
if config.package_format.archives() && !args.skip_binstall_test {
verify::verify_binstall(&checkout.root, &selected, &config.targets, &runner)?;
}
println!("Release completed and published artifacts verified.");

View File

@ -1,4 +1,5 @@
use crate::error::Error;
use clap::ValueEnum;
use serde::Deserialize;
use std::{fs, path::Path};
@ -37,6 +38,21 @@ pub struct Config {
pub locked: bool,
pub tag_prefix: String,
pub token_env: String,
pub package_format: PackageFormat,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum PackageFormat {
Tgz,
Binary,
Both,
}
impl PackageFormat {
pub fn archives(self) -> bool {
matches!(self, Self::Tgz | Self::Both)
}
pub fn binaries(self) -> bool {
matches!(self, Self::Binary | Self::Both)
}
}
#[derive(Default)]
pub struct Overrides {
@ -44,6 +60,7 @@ pub struct Overrides {
pub profile: Option<String>,
pub unlocked: bool,
pub tag_prefix: Option<String>,
pub package_format: Option<PackageFormat>,
}
pub fn load(path: Option<&Path>, overrides: Overrides) -> Result<Config, Error> {
if let Some(path) = path {
@ -61,9 +78,16 @@ fn parse(source: &str, overrides: Overrides) -> Result<Config, Error> {
let release = file.release.unwrap_or_default();
let package = file.package.unwrap_or_default();
let gitea = file.gitea.unwrap_or_default();
if package.format.as_deref().unwrap_or("tgz") != "tgz" {
return Err(Error("Only package.format = \"tgz\" is supported.".into()));
}
let package_format = match package.format.as_deref().unwrap_or("tgz") {
"tgz" => PackageFormat::Tgz,
"binary" => PackageFormat::Binary,
"both" => PackageFormat::Both,
_ => {
return Err(Error(
"package.format must be \"tgz\", \"binary\", or \"both\".".into(),
))
}
};
let mut config = Config {
targets: if overrides.targets.is_empty() {
build.targets.unwrap_or_else(|| {
@ -92,6 +116,7 @@ fn parse(source: &str, overrides: Overrides) -> Result<Config, Error> {
.or(release.tag_prefix)
.unwrap_or_else(|| "v".into()),
token_env: gitea.token_env.unwrap_or_else(|| "GITEA_TOKEN".into()),
package_format: overrides.package_format.unwrap_or(package_format),
};
if config.targets.is_empty() || config.targets.iter().any(|target| !valid_target(target)) {
return Err(Error(
@ -153,6 +178,12 @@ mod tests {
assert_eq!(config.tag_prefix, "");
assert!(parse("[build]\ntargets=['bad']", Overrides::default()).is_err());
assert!(parse("[package]\nformat='zip'", Overrides::default()).is_err());
assert_eq!(
parse("[package]\nformat='both'", Overrides::default())
.unwrap()
.package_format,
PackageFormat::Both
);
assert_eq!(load(None, Overrides::default()).unwrap().targets.len(), 3);
}
}

View File

@ -39,7 +39,12 @@ fn binstall(package: &Table) -> Result<Option<&Table>, Error> {
.ok_or_else(|| Error("package.metadata.binstall must be a table.".into()))
}
pub fn changes(path: &Path, repository: &str, prefix: &str) -> Result<Vec<Change>, Error> {
pub fn changes(
path: &Path,
repository: &str,
prefix: &str,
require_binstall: bool,
) -> Result<Vec<Change>, Error> {
let doc = document(path)?;
let package = package(&doc)?;
let mut result = Vec::new();
@ -54,6 +59,9 @@ pub fn changes(path: &Path, repository: &str, prefix: &str) -> Result<Vec<Change
expected: Some(repository.into()),
});
}
if !require_binstall {
return Ok(result);
}
let metadata = binstall(package)?;
let expected = policy::binstall_metadata(prefix);
for (key, desired) in &expected {
@ -144,7 +152,7 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("Cargo.toml");
fs::write(&path, "# keep this comment\n[package]\nname = 'demo'\nversion = '0.1.0'\nrepository = 'https://old.example/x/y' # keep inline\n[package.metadata.binstall]\npkg-fmt = 'zip'\ncustom = 'bad'\n").unwrap();
let issues = changes(&path, "https://example.com/x/y", "release-").unwrap();
let issues = changes(&path, "https://example.com/x/y", "release-", true).unwrap();
assert_eq!(issues.len(), 5);
let before = fs::read_to_string(&path).unwrap();
let preview = repair(&path, &issues, false).unwrap();
@ -152,7 +160,7 @@ mod tests {
assert!(preview.contains("# keep this comment"));
assert!(preview.contains("# keep inline"));
repair(&path, &issues, true).unwrap();
assert!(changes(&path, "https://example.com/x/y", "release-")
assert!(changes(&path, "https://example.com/x/y", "release-", true)
.unwrap()
.is_empty());
assert_eq!(
@ -165,9 +173,12 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("Cargo.toml");
fs::write(&path, "[package]\nname='demo'\nmetadata='oops'\n").unwrap();
assert!(changes(&path, "https://example.com/x/y", "v")
assert!(changes(&path, "https://example.com/x/y", "v", true)
.unwrap_err()
.to_string()
.contains("package.metadata must be a table"));
let issues = changes(&path, "https://example.com/x/y", "v", false).unwrap();
assert_eq!(issues.len(), 1);
assert_eq!(issues[0].key, "package.repository");
}
}

View File

@ -1,4 +1,4 @@
use crate::{error::Error, policy};
use crate::{build::TargetOutputs, config::PackageFormat, error::Error, policy};
use flate2::{Compression, GzBuilder};
use sha2::{Digest, Sha256};
use std::{
@ -11,22 +11,30 @@ use std::{
pub struct Artifact {
pub target: String,
pub path: PathBuf,
pub root: String,
pub binary: String,
pub contents: ArtifactContents,
pub sha256: String,
}
#[derive(Debug, Clone)]
pub enum ArtifactContents {
Archive { root: String, binaries: Vec<String> },
Binary,
}
pub fn package(
root: &Path,
name: &str,
version: &str,
binary: &str,
outputs: &[(String, PathBuf)],
outputs: &[TargetOutputs],
format: PackageFormat,
) -> Result<(Vec<Artifact>, PathBuf), Error> {
for (target, _) in outputs {
safe_component(&policy::archive_root(name, target, version))?;
safe_component(&policy::archive_name(name, target, version))?;
safe_component(&policy::binary_filename(binary, target))?;
for output in outputs {
safe_component(&policy::archive_root(name, &output.target, version))?;
safe_component(&policy::archive_name(name, &output.target, version))?;
for (binary, _) in &output.binaries {
safe_component(&policy::binary_filename(binary, &output.target))?;
safe_component(&policy::binary_asset_name(binary, &output.target, version))?;
}
}
let dist = root.join("dist");
if dist.is_symlink() {
@ -39,63 +47,97 @@ pub fn package(
.tempdir_in(&dist)
.map_err(|e| Error(format!("cannot create release staging directory: {e}")))?;
let mut artifacts = Vec::new();
for (target, source) in outputs {
let archive_root = policy::archive_root(name, target, version);
let filename = policy::archive_name(name, target, version);
let executable = policy::binary_filename(binary, target);
let path = staging.path().join(filename);
let metadata = fs::symlink_metadata(source)
.map_err(|e| Error(format!("cannot inspect binary {}: {e}", source.display())))?;
if !metadata.file_type().is_file() {
return Err(Error(format!(
"Build did not produce a regular binary: {}",
source.display()
)));
for output in outputs {
for (_, source) in &output.binaries {
let metadata = fs::symlink_metadata(source)
.map_err(|e| Error(format!("cannot inspect binary {}: {e}", source.display())))?;
if !metadata.file_type().is_file() {
return Err(Error(format!(
"Build did not produce a regular binary: {}",
source.display()
)));
}
}
let mode = if target.split('-').any(|part| part == "windows") {
0o644
} else {
unix_mode(&metadata) | 0o111
};
let output = File::create(&path)
.map_err(|e| Error(format!("cannot create archive {}: {e}", path.display())))?;
let mut gzip = GzBuilder::new()
.mtime(0)
.operating_system(255)
.write(output, Compression::default());
write_header(&mut gzip, &archive_root, 0o755, 0, b'5')?;
write_header(
&mut gzip,
&format!("{archive_root}/{executable}"),
mode,
metadata.len(),
b'0',
)?;
let mut input = File::open(source)
.map_err(|e| Error(format!("cannot open binary {}: {e}", source.display())))?;
let copied = io::copy(&mut input, &mut gzip)
.map_err(|e| Error(format!("cannot archive {}: {e}", source.display())))?;
if copied != metadata.len() {
return Err(Error(format!(
"Binary changed while packaging: {}",
source.display()
)));
if format.archives() {
let archive_root = policy::archive_root(name, &output.target, version);
let path = staging
.path()
.join(policy::archive_name(name, &output.target, version));
let archive = File::create(&path)
.map_err(|e| Error(format!("cannot create archive {}: {e}", path.display())))?;
let mut gzip = GzBuilder::new()
.mtime(0)
.operating_system(255)
.write(archive, Compression::default());
write_header(&mut gzip, &archive_root, 0o755, 0, b'5')?;
let mut names = Vec::new();
for (binary, source) in &output.binaries {
let metadata = fs::symlink_metadata(source).map_err(|e| {
Error(format!("cannot inspect binary {}: {e}", source.display()))
})?;
let executable = policy::binary_filename(binary, &output.target);
let mode = if output.target.split('-').any(|part| part == "windows") {
0o644
} else {
unix_mode(&metadata) | 0o111
};
write_header(
&mut gzip,
&format!("{archive_root}/{executable}"),
mode,
metadata.len(),
b'0',
)?;
let mut input = File::open(source)
.map_err(|e| Error(format!("cannot open binary {}: {e}", source.display())))?;
let copied = io::copy(&mut input, &mut gzip)
.map_err(|e| Error(format!("cannot archive {}: {e}", source.display())))?;
if copied != metadata.len() {
return Err(Error(format!(
"Binary changed while packaging: {}",
source.display()
)));
}
let padding = (512 - metadata.len() % 512) % 512;
gzip.write_all(&vec![0; padding as usize])
.map_err(|e| Error(format!("cannot pad archive: {e}")))?;
names.push(executable);
}
gzip.write_all(&[0; 1024])
.map_err(|e| Error(format!("cannot finish tar archive: {e}")))?;
gzip.finish()
.map_err(|e| Error(format!("cannot finish gzip archive: {e}")))?;
artifacts.push(Artifact {
target: output.target.clone(),
sha256: checksum(&path)?,
path,
contents: ArtifactContents::Archive {
root: archive_root,
binaries: names,
},
});
}
if format.binaries() {
for (binary, source) in &output.binaries {
let path =
staging
.path()
.join(policy::binary_asset_name(binary, &output.target, version));
fs::copy(source, &path).map_err(|e| {
Error(format!(
"cannot export binary {} to {}: {e}",
source.display(),
path.display()
))
})?;
artifacts.push(Artifact {
target: output.target.clone(),
sha256: checksum(&path)?,
path,
contents: ArtifactContents::Binary,
});
}
}
let padding = (512 - metadata.len() % 512) % 512;
gzip.write_all(&vec![0; padding as usize])
.map_err(|e| Error(format!("cannot pad archive: {e}")))?;
gzip.write_all(&[0; 1024])
.map_err(|e| Error(format!("cannot finish tar archive: {e}")))?;
gzip.finish()
.map_err(|e| Error(format!("cannot finish gzip archive: {e}")))?;
let sha256 = checksum(&path)?;
artifacts.push(Artifact {
target: target.clone(),
path,
root: archive_root,
binary: executable,
sha256,
});
}
let sums = staging.path().join("SHA256SUMS");
artifacts.sort_by(|a, b| a.path.file_name().cmp(&b.path.file_name()));
@ -215,26 +257,60 @@ mod tests {
fn archive_contract_and_reproducibility() {
let temp = tempfile::tempdir().unwrap();
let binary = temp.path().join("demo");
let helper = temp.path().join("helper");
fs::write(&binary, b"small executable").unwrap();
fs::write(&helper, b"helper executable").unwrap();
let outputs = [
("x86_64-unknown-linux-musl".to_owned(), binary.clone()),
("x86_64-pc-windows-gnu".to_owned(), binary),
TargetOutputs {
target: "x86_64-unknown-linux-musl".to_owned(),
binaries: vec![
("demo".into(), binary.clone()),
("helper".into(), helper.clone()),
],
},
TargetOutputs {
target: "x86_64-pc-windows-gnu".to_owned(),
binaries: vec![("demo".into(), binary), ("helper".into(), helper)],
},
];
let (first, sums) = package(temp.path(), "demo", "0.1.0", "demo", &outputs).unwrap();
assert_eq!(first.len(), 2);
assert_eq!(fs::read_to_string(sums).unwrap().lines().count(), 2);
let (second, _) = package(temp.path(), "demo", "0.1.0", "demo", &outputs).unwrap();
let (first, sums) =
package(temp.path(), "demo", "0.1.0", &outputs, PackageFormat::Both).unwrap();
assert_eq!(first.len(), 6);
assert_eq!(fs::read_to_string(sums).unwrap().lines().count(), 6);
let names = first
.iter()
.map(|artifact| artifact.path.file_name().unwrap().to_str().unwrap())
.collect::<Vec<_>>();
assert!(names.contains(&"demo-x86_64-unknown-linux-musl-v0.1.0"));
assert!(names.contains(&"helper-x86_64-pc-windows-gnu-v0.1.0.exe"));
let (binary_only, _) = package(
temp.path(),
"demo",
"0.1.0",
&outputs,
PackageFormat::Binary,
)
.unwrap();
assert_eq!(binary_only.len(), 4);
assert!(binary_only
.iter()
.all(|artifact| matches!(&artifact.contents, ArtifactContents::Binary)));
let (second, _) =
package(temp.path(), "demo", "0.1.0", &outputs, PackageFormat::Both).unwrap();
for (one, two) in first.iter().zip(second.iter()) {
assert_eq!(fs::read(&one.path).unwrap(), fs::read(&two.path).unwrap());
assert_eq!(one.sha256, checksum(&one.path).unwrap());
let ArtifactContents::Archive { root, binaries } = &one.contents else {
continue;
};
let mut tar = Vec::new();
GzDecoder::new(File::open(&one.path).unwrap())
.read_to_end(&mut tar)
.unwrap();
assert_eq!(&tar[..one.root.len()], one.root.as_bytes());
assert_eq!(&tar[..root.len()], root.as_bytes());
assert_eq!(tar[156], b'5');
let file_header = &tar[512..1024];
let expected = format!("{}/{}", one.root, one.binary);
let expected = format!("{}/{}", root, binaries[0]);
assert_eq!(&file_header[..expected.len()], expected.as_bytes());
assert_eq!(file_header[156], b'0');
assert_eq!(&tar[1024..1024 + 16], b"small executable");
@ -251,25 +327,22 @@ mod tests {
let temp = tempfile::tempdir().unwrap();
let binary = temp.path().join("demo");
fs::write(&binary, "binary").unwrap();
let outputs = [TargetOutputs {
target: "x86_64-unknown-linux-musl".into(),
binaries: vec![("demo".into(), binary.clone())],
}];
assert!(package(
temp.path(),
"../escape",
"0.1.0",
"demo",
&[("x86_64-unknown-linux-musl".into(), binary.clone())]
&outputs,
PackageFormat::Tgz,
)
.is_err());
#[cfg(unix)]
{
std::os::unix::fs::symlink(temp.path(), temp.path().join("dist")).unwrap();
assert!(package(
temp.path(),
"demo",
"0.1.0",
"demo",
&[("x86_64-unknown-linux-musl".into(), binary)]
)
.is_err());
assert!(package(temp.path(), "demo", "0.1.0", &outputs, PackageFormat::Tgz,).is_err());
}
}
}

View File

@ -18,6 +18,10 @@ pub fn binary_filename(binary: &str, target: &str) -> String {
}
}
pub fn binary_asset_name(binary: &str, target: &str, version: &str) -> String {
binary_filename(&format!("{binary}-{target}-v{version}"), target)
}
pub fn binstall_metadata(prefix: &str) -> [(&'static str, String); 3] {
let root = archive_root("{ name }", "{ target }", "{ version }");
[
@ -44,6 +48,10 @@ mod tests {
);
assert_eq!(binary_filename("demo", "x86_64-pc-windows-gnu"), "demo.exe");
assert_eq!(binary_filename("demo", "x86_64-unknown-linux-musl"), "demo");
assert_eq!(
binary_asset_name("demo", "x86_64-pc-windows-gnu", "0.3.1"),
"demo-x86_64-pc-windows-gnu-v0.3.1.exe"
);
let metadata = binstall_metadata("release-");
assert_eq!(
metadata[0].1,

View File

@ -63,7 +63,12 @@ pub fn plan(
));
}
}
let changes = manifest::changes(&project.manifest, repository, &config.tag_prefix)?;
let changes = manifest::changes(
&project.manifest,
repository,
&config.tag_prefix,
config.package_format.archives(),
)?;
let manifest_old = fs::read_to_string(&project.manifest)
.map_err(|e| Error(format!("cannot read manifest: {e}")))?;
let manifest_new = manifest::repair(&project.manifest, &changes, false)?;
@ -462,6 +467,7 @@ mod tests {
locked: true,
tag_prefix: "v".into(),
token_env: "GITEA_TOKEN".into(),
package_format: crate::config::PackageFormat::Tgz,
};
(temp, project, config, runner)
}

View File

@ -9,7 +9,7 @@ use std::{
pub struct SelectedPackage {
pub name: String,
pub version: String,
pub binary: String,
pub binaries: Vec<String>,
pub manifest: PathBuf,
pub repository: Option<String>,
pub target_directory: PathBuf,
@ -174,9 +174,9 @@ pub fn inspect(
.iter()
.filter(|t| t.kind.iter().any(|kind| kind == "bin"))
.collect();
if binaries.len() != 1 {
if binaries.is_empty() {
return Err(Error(format!(
"Package {:?} must have exactly one binary; discovered: {}",
"Package {:?} must have at least one binary; discovered: {}",
selected.name,
binaries
.iter()
@ -185,7 +185,10 @@ pub fn inspect(
.join(", ")
)));
}
for value in [&selected.name, &selected.version, &binaries[0].name] {
for value in std::iter::once(&selected.name)
.chain(std::iter::once(&selected.version))
.chain(binaries.iter().map(|binary| &binary.name))
{
if !safe_component(value) {
return Err(Error("Unsafe package, version or binary filename.".into()));
}
@ -219,7 +222,7 @@ pub fn inspect(
Ok(SelectedPackage {
name: selected.name,
version: selected.version,
binary: binaries[0].name.clone(),
binaries: binaries.iter().map(|binary| binary.name.clone()).collect(),
manifest: member_manifest,
repository: selected.repository,
target_directory: metadata.target_directory,
@ -370,7 +373,7 @@ mod tests {
)
.unwrap();
assert_eq!(selected.name, "solo");
assert_eq!(selected.binary, "solo");
assert_eq!(selected.binaries, ["solo"]);
let workspace = tempfile::tempdir().unwrap();
write(
@ -402,13 +405,13 @@ mod tests {
assert_eq!(
inspect(root, Some("two"), &Runner::new("GITEA_TOKEN"))
.unwrap()
.binary,
"two"
.binaries,
["two"]
);
}
#[test]
fn rejects_library_and_multiple_binaries() {
fn rejects_library_and_accepts_multiple_binaries() {
let temp = tempfile::tempdir().unwrap();
write(
temp.path(),
@ -420,13 +423,15 @@ mod tests {
assert!(inspect(root, None, &Runner::new("GITEA_TOKEN"))
.unwrap_err()
.to_string()
.contains("exactly one binary"));
.contains("at least one binary"));
write(temp.path(), "src/main.rs", "fn main() {}\n");
write(temp.path(), "src/bin/extra.rs", "fn main() {}\n");
assert!(inspect(root, None, &Runner::new("GITEA_TOKEN"))
.unwrap_err()
.to_string()
.contains("exactly one binary"));
assert_eq!(
inspect(root, None, &Runner::new("GITEA_TOKEN"))
.unwrap()
.binaries,
["demo", "extra"]
);
}
#[test]

View File

@ -1,6 +1,6 @@
use crate::{
error::Error,
package::{self, Artifact},
package::{self, Artifact, ArtifactContents},
policy,
project::SelectedPackage,
runner::Runner,
@ -25,6 +25,9 @@ pub fn asset_url(repository: &str, tag: &str, filename: &str) -> String {
}
pub fn verify_archive(path: &Path, artifact: &Artifact) -> Result<(), Error> {
let ArtifactContents::Archive { root, binaries } = &artifact.contents else {
return Err(Error(format!("{} is not an archive.", path.display())));
};
let mut tar = Vec::new();
let file =
File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;
@ -36,44 +39,52 @@ pub fn verify_archive(path: &Path, artifact: &Artifact) -> Result<(), Error> {
}
let directory = &tar[..512];
let first = member_name(directory)?;
if first != artifact.root || directory[156] != b'5' {
if first != *root || directory[156] != b'5' {
return Err(Error(format!(
"{}: archive root does not match binstall metadata.",
path.display()
)));
}
let binary = &tar[512..1024];
let second = member_name(binary)?;
if second != format!("{}/{}", artifact.root, artifact.binary) || binary[156] != b'0' {
return Err(Error(format!(
"{}: archive binary does not match binstall metadata.",
path.display()
)));
let mut offset = 512_usize;
for expected in binaries {
let header_end = offset
.checked_add(512)
.ok_or_else(|| Error("Archive size overflow.".into()))?;
if header_end > tar.len() {
return Err(Error(format!(
"{}: truncated binary header.",
path.display()
)));
}
let header = &tar[offset..header_end];
if member_name(header)? != format!("{root}/{expected}") || header[156] != b'0' {
return Err(Error(format!(
"{}: archive binary does not match binstall metadata.",
path.display()
)));
}
let mode = octal(&header[100..108])?;
if !artifact.target.split('-').any(|part| part == "windows") && mode & 0o111 == 0 {
return Err(Error(format!(
"{}: binary is not executable.",
path.display()
)));
}
let size = usize::try_from(octal(&header[124..136])?)
.map_err(|_| Error("Archive size overflow.".into()))?;
let rounded = size
.checked_add(511)
.ok_or_else(|| Error("Archive size overflow.".into()))?
/ 512
* 512;
offset = header_end
.checked_add(rounded)
.ok_or_else(|| Error("Archive size overflow.".into()))?;
}
let mode = octal(&binary[100..108])?;
if !artifact.target.split('-').any(|part| part == "windows") && mode & 0o111 == 0 {
return Err(Error(format!(
"{}: binary is not executable.",
path.display()
)));
}
let size = octal(&binary[124..136])?;
let rounded = size
.checked_add(511)
.ok_or_else(|| Error("Archive size overflow.".into()))?
/ 512
* 512;
let end = 1024_u64
.checked_add(rounded)
.and_then(|n| n.checked_add(1024))
let end = offset
.checked_add(1024)
.ok_or_else(|| Error("Archive size overflow.".into()))?;
if end > tar.len() as u64 {
return Err(Error(format!(
"{}: truncated binary or tar footer.",
path.display()
)));
}
if tar[(end - 1024) as usize..].iter().any(|b| *b != 0) {
if end > tar.len() || tar[offset..].iter().any(|b| *b != 0) {
return Err(Error(format!(
"{}: archive contains unexpected members.",
path.display()
@ -187,8 +198,15 @@ pub fn verify_published(
)));
}
if let Some(artifact) = artifacts.iter().find(|a| a.path == local) {
verify_archive(&path, artifact)?;
println!("Verified URL, checksum and archive: {}", artifact.target);
match &artifact.contents {
ArtifactContents::Archive { .. } => {
verify_archive(&path, artifact)?;
println!("Verified URL, checksum and archive: {}", artifact.target);
}
ArtifactContents::Binary => {
println!("Verified URL and checksum: {}", filename);
}
}
}
}
println!("Verified published SHA256SUMS");
@ -252,11 +270,13 @@ fn verify_binstall_with_options(
.to_str()
.ok_or_else(|| Error("Cargo home path is not UTF-8.".into()))?;
runner.output_with("cargo", &borrowed, root, &[("CARGO_HOME", cargo_home)], &[])?;
let binary = install.join(policy::binary_filename(&project.binary, target));
if !binary.is_file() {
return Err(Error(format!(
"cargo-binstall did not install the expected binary for {target}."
)));
for name in &project.binaries {
let binary = install.join(policy::binary_filename(name, target));
if !binary.is_file() {
return Err(Error(format!(
"cargo-binstall did not install {name:?} for {target}."
)));
}
}
println!("cargo-binstall installation verified: {target}");
}
@ -266,6 +286,14 @@ fn verify_binstall_with_options(
#[cfg(test)]
mod tests {
use super::*;
use crate::{build::TargetOutputs, config::PackageFormat};
fn outputs(target: &str, binary: std::path::PathBuf) -> Vec<TargetOutputs> {
vec![TargetOutputs {
target: target.into(),
binaries: vec![("demo".into(), binary)],
}]
}
#[test]
#[ignore = "requires RUST_RELEASE_LIVE_* variables and a disposable Gitea release"]
fn live_release_downloads_match_local_artifacts() {
@ -288,8 +316,10 @@ mod tests {
target: (*target).into(),
sha256: package::checksum(&path)?,
path,
root: policy::archive_root(&name, target, &version),
binary: policy::binary_filename(&name, target),
contents: ArtifactContents::Archive {
root: policy::archive_root(&name, target, &version),
binaries: vec![policy::binary_filename(&name, target)],
},
})
})
.collect::<Result<Vec<_>, Error>>()
@ -316,7 +346,7 @@ mod tests {
let project = SelectedPackage {
name: name.clone(),
version: required("RUST_RELEASE_LIVE_VERSION"),
binary: name,
binaries: vec![name],
manifest,
repository: Some(required("RUST_RELEASE_LIVE_REPOSITORY")),
target_directory: root.join("target"),
@ -344,8 +374,8 @@ mod tests {
temp.path(),
"demo",
"0.1.0",
"demo",
&[("x86_64-unknown-linux-musl".into(), binary)],
&outputs("x86_64-unknown-linux-musl", binary),
PackageFormat::Tgz,
)
.unwrap();
let filename = artifacts[0]
@ -394,8 +424,8 @@ mod tests {
temp.path(),
"demo",
"0.1.0",
"demo",
&[("x86_64-unknown-linux-musl".into(), binary)],
&outputs("x86_64-unknown-linux-musl", binary),
PackageFormat::Tgz,
)
.unwrap();
let bodies = [
@ -459,12 +489,15 @@ mod tests {
.map(|target| {
let binary = temp.path().join(format!("binary-{target}"));
fs::write(&binary, format!("fixture binary for {target}"))?;
Ok((target.clone(), binary))
Ok(TargetOutputs {
target: target.clone(),
binaries: vec![("demo".into(), binary)],
})
})
.collect::<Result<Vec<_>, std::io::Error>>()
.unwrap();
let (artifacts, _) =
package::package(temp.path(), "demo", "0.1.0", "demo", &outputs).unwrap();
package::package(temp.path(), "demo", "0.1.0", &outputs, PackageFormat::Tgz).unwrap();
let archives = artifacts
.iter()
.map(|artifact| {
@ -526,7 +559,7 @@ mod tests {
let project = SelectedPackage {
name: "demo".into(),
version: "0.1.0".into(),
binary: "demo".into(),
binaries: vec!["demo".into()],
manifest,
repository: Some(repository),
target_directory: temp.path().join("target"),
@ -552,8 +585,8 @@ mod tests {
temp.path(),
"demo",
"0.1.0",
"demo",
&[("x86_64-unknown-linux-musl".into(), binary)],
&outputs("x86_64-unknown-linux-musl", binary),
PackageFormat::Tgz,
)
.unwrap();
verify_archive(&artifacts[0].path, &artifacts[0]).unwrap();
@ -576,7 +609,7 @@ mod tests {
let project = SelectedPackage {
name: "demo".into(),
version: "0.1.0".into(),
binary: "demo".into(),
binaries: vec!["demo".into()],
manifest: temp.path().join("Cargo.toml"),
repository: None,
target_directory: temp.path().join("target"),