Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

all: Version improvements #268

Merged
merged 5 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ default-members = [
resolver = "2"

[workspace.package]
version = "0.1.0"
edition = "2021"
rust-version = "1.78"

[workspace.dependencies]
blsforme = { git = "https://github.com/serpent-os/blsforme.git", rev = "0aaece601fe4d11025382fa6e0e45deb1d668c92" }
Expand Down
4 changes: 3 additions & 1 deletion boulder/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
[package]
name = "boulder"
version = "0.1.0"
edition.workspace = true
version.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
config = { path = "../crates/config" }
container = { path = "../crates/container" }
moss = { path = "../moss" }
serpent_buildinfo = { path = "../crates/serpent_buildinfo" }
stone = { path = "../crates/stone" }
stone_recipe = { path = "../crates/stone_recipe" }
tui = { path = "../crates/tui" }
Expand Down
31 changes: 18 additions & 13 deletions boulder/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ mod build;
mod chroot;
mod profile;
mod recipe;
mod version;

#[derive(Debug, Parser)]
#[command(version = version())]
pub struct Command {
#[command(flatten)]
pub global: Global,
Expand All @@ -23,6 +23,14 @@ pub struct Command {

#[derive(Debug, Args)]
pub struct Global {
#[arg(
short,
long = "verbose",
help = "Prints additional information about what boulder is doing",
default_value = "false",
global = true
)]
pub verbose: bool,
#[arg(long, global = true)]
pub cache_dir: Option<PathBuf>,
#[arg(long, global = true)]
Expand All @@ -39,19 +47,28 @@ pub enum Subcommand {
Chroot(chroot::Command),
Profile(profile::Command),
Recipe(recipe::Command),
Version(version::Command),
}

pub fn process() -> Result<(), Error> {
let args = replace_aliases(std::env::args());
let Command { global, subcommand } = Command::parse_from(args);

if global.verbose {
match subcommand {
Subcommand::Version(_) => (),
_ => version::print(),
}
}

let env = Env::new(global.cache_dir, global.config_dir, global.data_dir, global.moss_root)?;

match subcommand {
Subcommand::Build(command) => build::handle(command, env)?,
Subcommand::Chroot(command) => chroot::handle(command, env)?,
Subcommand::Profile(command) => profile::handle(command, env)?,
Subcommand::Recipe(command) => recipe::handle(command, env)?,
Subcommand::Version(command) => version::handle(command),
}

Ok(())
Expand Down Expand Up @@ -94,15 +111,3 @@ pub enum Error {
#[error("recipe")]
Recipe(#[from] recipe::Error),
}

fn version() -> String {
use moss::environment;

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

let hash = environment::GIT_HASH
.map(|hash| format!(" ({hash})"))
.unwrap_or_default();

format!("{VERSION}{hash}")
}
34 changes: 34 additions & 0 deletions boulder/src/cli/version.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// SPDX-FileCopyrightText: Copyright © 2020-2024 Serpent OS Developers
//
// SPDX-License-Identifier: MPL-2.0

use clap::Parser;

#[derive(Debug, Parser)]
#[command(about = "Print version info and exit")]
pub struct Command {
#[arg(
long = "full",
help = "Print the full build and version info",
default_value = "false"
)]
full: bool,
}

pub fn handle(command: Command) {
if command.full {
print_full()
} else {
print()
}
}

/// Print program version
pub fn print() {
println!("boulder {}", serpent_buildinfo::get_simple_version());
}

/// Print additional build information
pub fn print_full() {
println!("boulder {}", serpent_buildinfo::get_full_version());
}
3 changes: 2 additions & 1 deletion crates/config/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
[package]
name = "config"
version = "0.1.0"
edition.workspace = true
version.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
3 changes: 2 additions & 1 deletion crates/container/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
[package]
name = "container"
version = "0.1.0"
edition.workspace = true
version.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
3 changes: 2 additions & 1 deletion crates/dag/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
[package]
name = "dag"
version = "0.1.0"
edition.workspace = true
version.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
3 changes: 2 additions & 1 deletion crates/fnmatch/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
[package]
name = "fnmatch"
version = "0.1.0"
edition.workspace = true
version.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
13 changes: 13 additions & 0 deletions crates/serpent_buildinfo/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "serpent_buildinfo"
edition.workspace = true
version.workspace = true
rust-version.workspace = true
build = "build.rs"

[dependencies]
chrono.workspace = true

[build-dependencies]
chrono.workspace = true
thiserror.workspace = true
149 changes: 149 additions & 0 deletions crates/serpent_buildinfo/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// build.rs
use std::os::unix::ffi::OsStringExt;

use chrono::{DateTime, Utc};

/// Returns value of given environment variable or error if missing.
///
/// This also outputs necessary ‘cargo:rerun-if-env-changed’ tag to make sure
/// build script is rerun if the environment variable changes.
fn env(key: &str) -> Result<std::ffi::OsString, Box<dyn std::error::Error>> {
println!("cargo:rerun-if-env-changed={}", key);
std::env::var_os(key).ok_or_else(|| Box::from(format!("Missing `{}` environmental variable", key)))
}

/// Calls program with given arguments and returns its standard output. If
/// calling the program fails or it exits with non-zero exit status returns an
/// error.
fn command(prog: &str, args: &[&str], cwd: Option<std::path::PathBuf>) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
println!("cargo:rerun-if-env-changed=PATH");
let mut cmd = std::process::Command::new(prog);
cmd.args(args);
cmd.stderr(std::process::Stdio::inherit());
if let Some(cwd) = cwd {
cmd.current_dir(cwd);
}
let out = cmd.output()?;
if out.status.success() {
let mut stdout = out.stdout;
if let Some(b'\n') = stdout.last() {
stdout.pop();
if let Some(b'\r') = stdout.last() {
stdout.pop();
}
}
Ok(stdout)
} else if let Some(code) = out.status.code() {
Err(Box::from(format!("{}: terminated with {}", prog, code)))
} else {
Err(Box::from(format!("{}: killed by signal", prog)))
}
}

/// Checks to see if we're building from a git source and if so attempts to gather information about the git status
fn get_git_info() -> Result<(), Box<dyn std::error::Error>> {
let pkg_dir = std::path::PathBuf::from(env("CARGO_MANIFEST_DIR")?);
let git_dir = command("git", &["rev-parse", "--git-dir"], Some(pkg_dir.clone()));
let git_dir = match git_dir {
Ok(git_dir) => {
println!("cargo:rustc-cfg=BUILDINFO_IS_GIT_BUILD");

std::path::PathBuf::from(std::ffi::OsString::from_vec(git_dir))
}
Err(msg) => {
// We're not in a git repo, most likely we're building from a source archive
println!("cargo:warning=unable to determine git version (not in git repository?)");
println!("cargo:warning={}", msg);

// It's unlikely, but possible that someone could run git init. Might as well catch that.
println!("cargo::rerun-if-changed={}/.git", pkg_dir.display());
return Ok(());
}
};

// Make Cargo rerun us if currently checked out commit or the state of the
// working tree changes. We try to accomplish that by looking at a few
// crucial git state files. This probably may result in some false
// negatives but it’s best we’ve got.
for subpath in ["HEAD", "logs/HEAD", "index"] {
let path = git_dir.join(subpath).canonicalize()?;
println!("cargo:rerun-if-changed={}", path.display());
}

// Get the full git hash
let args = &["rev-parse", "--output-object-format=sha1", "HEAD"];
let out = command("git", args, None)?;
match String::from_utf8_lossy(&out) {
std::borrow::Cow::Borrowed(full_hash) => {
println!("cargo:rustc-env=BUILDINFO_GIT_FULL_HASH={}", full_hash.trim());
}
std::borrow::Cow::Owned(full_hash) => return Err(Box::from(format!("git: Invalid output: {}", full_hash))),
}

// Get the short git hash
let args = &["rev-parse", "--output-object-format=sha1", "--short", "HEAD"];
let out = command("git", args, None)?;
match String::from_utf8_lossy(&out) {
std::borrow::Cow::Borrowed(short_hash) => {
println!("cargo:rustc-env=BUILDINFO_GIT_SHORT_HASH={}", short_hash.trim());
}
std::borrow::Cow::Owned(short_hash) => return Err(Box::from(format!("git: Invalid output: {}", short_hash))),
}

// Get whether this is built from a dirty tree
let args = &["status", "--porcelain"];
let out = command("git", args, None)?;
match String::from_utf8_lossy(&out) {
std::borrow::Cow::Borrowed(output) => match output.trim().len() {
0 => {}
_ => println!("cargo:rustc-cfg=BUILDINFO_IS_DIRTY"),
},
std::borrow::Cow::Owned(output) => return Err(Box::from(format!("git: Invalid output: {}", output))),
}

// Get the commit summary
let args = &["show", "--format=\"%s\"", "-s"];
let out = command("git", args, None)?;
match String::from_utf8_lossy(&out) {
std::borrow::Cow::Borrowed(summary) => {
println!("cargo:rustc-env=BUILDINFO_GIT_SUMMARY={}", summary.trim());
}
std::borrow::Cow::Owned(summary) => return Err(Box::from(format!("git: Invalid output: {}", summary))),
}

Ok(())
}

fn get_build_time() -> Result<(), Box<dyn std::error::Error>> {
// Propagate SOURCE_DATE_EPOCH if set
if let Ok(epoch_env) = env("SOURCE_DATE_EPOCH") {
if let Ok(seconds) = epoch_env.to_string_lossy().parse::<i64>() {
if let Some(time) = DateTime::from_timestamp(seconds, 0) {
println!("cargo:rustc-env=BUILDINFO_BUILD_TIME={}", time.timestamp());
return Ok(());
}
}
}

println!("cargo:rustc-env=BUILDINFO_BUILD_TIME={}", Utc::now().timestamp());
Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
// This should include all top-level directories that contain source code or otherwise modify the build in meaningful ways
let top_level = std::path::PathBuf::from("../..").canonicalize()?;
println!("cargo::rerun-if-changed={}/boulder", top_level.display());
println!("cargo::rerun-if-changed={}/crates", top_level.display());
println!("cargo::rerun-if-changed={}/moss", top_level.display());
println!("cargo::rerun-if-changed={}/test", top_level.display());
println!("cargo::rerun-if-changed={}/Cargo.toml", top_level.display());

let version = env("CARGO_PKG_VERSION")?;
println!("cargo:rustc-env=BUILDINFO_VERSION={}", version.to_string_lossy());

get_build_time()?;

get_git_info()?;

Ok(())
}
Loading
Loading