Skip to content
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
197 changes: 197 additions & 0 deletions crates/common/src/target.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use blake3::Hasher;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::io::Write;
use std::str::FromStr;

/// A supported CPU architecture.
#[derive(Debug, Clone, Default, Hash, PartialEq, Eq, Serialize, Deserialize)]
Expand All @@ -19,6 +21,43 @@ impl Arch {
}
}

/// Error from parsing an [`Arch`] out of a string the user typed on the
/// command line or in a config file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArchParseError {
input: String,
}

impl fmt::Display for ArchParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"unsupported architecture: {}. Use 'amd64' or 'arm64'.",
self.input
)
}
}

impl std::error::Error for ArchParseError {}

impl FromStr for Arch {
type Err = ArchParseError;

/// Parse an arch from the strings a user is likely to type on the
/// command line. Accepts both the Minimal-native names (`amd64`,
/// `arm64`) and the Rust target-triple forms (`x86_64`, `aarch64`)
/// so that `uname -m` output works verbatim on both platforms.
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"amd64" | "x86_64" => Ok(Arch::Amd64),
"arm64" | "aarch64" => Ok(Arch::Arm64),
_ => Err(ArchParseError {
input: s.to_string(),
}),
}
}
}

/// A supported OS.
#[derive(Debug, Clone, Default, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub enum OS {
Expand All @@ -36,6 +75,37 @@ impl OS {
}
}

/// Error from parsing an [`OS`] out of a string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OsParseError {
input: String,
}

impl fmt::Display for OsParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unsupported OS: {}. Use 'linux' or 'macos'.", self.input)
}
}

impl std::error::Error for OsParseError {}

impl FromStr for OS {
type Err = OsParseError;

/// Parse an OS from the short lowercase strings that appear in
/// `Target::as_ref()` output and that consumers (build.ncl target
/// expressions, CLI args) type by hand.
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"linux" => Ok(OS::Linux),
"macos" => Ok(OS::MacOS),
_ => Err(OsParseError {
input: s.to_string(),
}),
}
}
}

/// The description of a system where software runs.
#[derive(Debug, Clone, Default, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct Target {
Expand Down Expand Up @@ -131,3 +201,130 @@ impl AsRef<str> for Target {
}
}
}

/// Error from parsing a [`Target`] out of an `<arch>/<os>` string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TargetParseError {
/// The string didn't match the required `<arch>/<os>` shape.
Shape(String),
/// The arch segment didn't parse.
Arch(ArchParseError),
/// The OS segment didn't parse.
Os(OsParseError),
}

impl fmt::Display for TargetParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TargetParseError::Shape(s) => write!(
f,
"target {s:?} is not in the expected <arch>/<os> form (e.g. 'amd64/linux')"
),
TargetParseError::Arch(e) => write!(f, "target: {e}"),
TargetParseError::Os(e) => write!(f, "target: {e}"),
}
}
}

impl std::error::Error for TargetParseError {}

impl FromStr for Target {
type Err = TargetParseError;

/// Parse a [`Target`] from the `<arch>/<os>` string produced by
/// [`Target::as_ref`] — round-trips with that impl. Arch and OS
/// parsing delegate to [`Arch::from_str`] / [`OS::from_str`] so the
/// accepted alias set stays consistent across every consumer.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (arch_str, os_str) = s
.split_once('/')
.ok_or_else(|| TargetParseError::Shape(s.to_string()))?;
let arch = arch_str.parse::<Arch>().map_err(TargetParseError::Arch)?;
let os = os_str.parse::<OS>().map_err(TargetParseError::Os)?;
Ok(Target::new(arch, os))
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn arch_parses_amd64_and_alias() {
assert_eq!("amd64".parse::<Arch>().unwrap(), Arch::Amd64);
assert_eq!("x86_64".parse::<Arch>().unwrap(), Arch::Amd64);
}

#[test]
fn arch_parses_arm64_and_alias() {
assert_eq!("arm64".parse::<Arch>().unwrap(), Arch::Arm64);
assert_eq!("aarch64".parse::<Arch>().unwrap(), Arch::Arm64);
}

#[test]
fn arch_rejects_unknown_and_names_input() {
let err = "riscv64".parse::<Arch>().unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("riscv64") && msg.contains("'amd64'") && msg.contains("'arm64'"),
"error should name the bad input and list valid options, got: {msg}",
);
}

#[test]
fn arch_rejects_case_mismatch() {
// Case-sensitive — "AMD64" isn't an accepted spelling, users
// should stick to the lowercase form that matches uname -m /
// rust target triples.
assert!("AMD64".parse::<Arch>().is_err());
assert!("ARM64".parse::<Arch>().is_err());
}

#[test]
fn arch_rejects_empty_string() {
assert!("".parse::<Arch>().is_err());
}

#[test]
fn os_parses_both_variants() {
assert_eq!("linux".parse::<OS>().unwrap(), OS::Linux);
assert_eq!("macos".parse::<OS>().unwrap(), OS::MacOS);
}

#[test]
fn os_rejects_unknown() {
let err = "freebsd".parse::<OS>().unwrap_err();
assert!(format!("{err}").contains("freebsd"));
}

#[test]
fn target_roundtrips_with_as_ref() {
// Every representation in Target::all() must parse back to the
// same value — keeps as_ref and from_str in lockstep.
for expected in Target::all() {
let s: &str = expected.as_ref();
let parsed: Target = s.parse().expect("every Target::all() must parse");
assert_eq!(&parsed, expected, "roundtrip failed for {s}");
}
}

#[test]
fn target_rejects_missing_separator() {
let err = "amd64linux".parse::<Target>().unwrap_err();
assert!(matches!(err, TargetParseError::Shape(_)));
}

#[test]
fn target_propagates_arch_error() {
let err = "riscv64/linux".parse::<Target>().unwrap_err();
assert!(matches!(err, TargetParseError::Arch(_)));
assert!(format!("{err}").contains("riscv64"));
}

#[test]
fn target_propagates_os_error() {
let err = "amd64/freebsd".parse::<Target>().unwrap_err();
assert!(matches!(err, TargetParseError::Os(_)));
assert!(format!("{err}").contains("freebsd"));
}
}
8 changes: 4 additions & 4 deletions crates/decode/src/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -907,12 +907,12 @@ impl BuildDecl {
program,
)?)
.unwrap();
match Target::all().iter().find(|t| t.as_ref() == target_str) {
None => Err(Error::InvalidTarget { files: program.files(), got: target_str, pos: rt.pos(program.pos_table()) }),
Some(t) => {
target = Some(t.clone());
match target_str.parse::<Target>() {
Ok(t) => {
target = Some(t);
Ok(())
}
Err(_) => Err(Error::InvalidTarget { files: program.files(), got: target_str, pos: rt.pos(program.pos_table()) }),
}
} else {
Ok(())
Expand Down
66 changes: 65 additions & 1 deletion crates/minimal/src/cmd_dump.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::{fmt::Display, io::stdout};

use common::Target;
use common::fuzzy_search::fuzzy_match;
use common::target::{Arch, OS};
use decode::AttrValue;
use graph::{BuildDep, BuildOutput, BuildSpec, BuildSpecRef, Graph, RuntimeDep, SourceInput};
use mctx::{Cache, Context, Error};
Expand All @@ -18,6 +20,15 @@ pub struct DumpArgs {
#[arg(long, default_value_t = false)]
pub exact: bool,

/// Target architecture to evaluate packages against (e.g., "amd64",
/// "arm64"). When a package's `build_deps` uses
/// `match { arch = 'Amd64 } => ..., { arch = 'Arm64 } => ... } target`
/// to select between per-arch source URLs, only the matching arm's
/// output appears in the dump. Overrides the host default so tools
/// downstream can aggregate both arches by running the dump twice.
#[arg(long)]
pub arch: Option<String>,

pub name: Option<String>,
}

Expand Down Expand Up @@ -120,7 +131,8 @@ impl From<&AttrValue> for PkgAttr {
pub async fn cmd_dump(args: DumpArgs, ctx: &mut Context) -> Result<(), Error> {
let mut out_packages = Vec::new();

let graph = ctx.graph_from_all_packages()?;
let target = resolve_target(args.arch.as_deref())?;
let graph = ctx.graph_from_all_packages_with_target(target)?;
let cache = ctx.local_cache();

if args.kind.packages {
Expand Down Expand Up @@ -219,3 +231,55 @@ fn pkg_ref_from_input(g: &Graph, i: &BuildDep, _c: &Cache) -> Result<PkgRef, Err
_ => todo!("bsi variant {:?}", i),
}
}

/// Resolve the `--arch` flag into a [`Target`]. Delegates the string
/// parsing to the shared `Arch::from_str` impl in common so the alias
/// set (arm64/aarch64, amd64/x86_64) stays consistent with every other
/// consumer. When the flag is absent, defaults to [`Target::host`]. OS
/// is always Linux — dump consumers want per-arch evaluation of the
/// same pkgs repo, not cross-OS.
fn resolve_target(arch: Option<&str>) -> Result<Target, Error> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make or use an existing method on Target or Arch: the generic problem of going from an &str into the specific type is something we are bound to use half a dozen times in various places.

let Some(arch_str) = arch else {
return Ok(Target::host());
};
let arch: Arch = arch_str
.parse()
.map_err(|e: common::target::ArchParseError| Error::Other(e.into()))?;
Ok(Target::new(arch, OS::Linux))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn resolve_target_defaults_to_host_when_arg_missing() {
let target = resolve_target(None).unwrap();
assert_eq!(target.arch(), Target::host().arch());
assert_eq!(target.os(), Target::host().os());
}

#[test]
fn resolve_target_wraps_parsed_arch_with_linux_os() {
let target = resolve_target(Some("amd64")).unwrap();
assert!(matches!(target.arch(), Arch::Amd64));
assert!(matches!(target.os(), OS::Linux));

let target = resolve_target(Some("arm64")).unwrap();
assert!(matches!(target.arch(), Arch::Arm64));
assert!(matches!(target.os(), OS::Linux));
}

#[test]
fn resolve_target_propagates_arch_parse_error() {
// String-to-arch parsing (and its error message) lives in
// common::target; this test confirms cmd_dump surfaces that
// error to the caller rather than silently eating it.
let err = resolve_target(Some("riscv64")).unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("riscv64"),
"error should name the bad input, got: {msg}"
);
}
}
24 changes: 8 additions & 16 deletions crates/minimal/src/cmd_materialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,14 @@ pub async fn cmd_materialize(args: MaterializeArgs, ctx: &mut Context) -> Result
}
};

// Resolve target architecture: CLI flag > minimal.toml > host default
let arch_str = args
.arch
.or(output.arch)
.unwrap_or_else(|| match Target::host().arch() {
Arch::Arm64 => "arm64".to_string(),
Arch::Amd64 => "amd64".to_string(),
});
let arch = match arch_str.as_str() {
"arm64" | "aarch64" => Arch::Arm64,
"amd64" | "x86_64" => Arch::Amd64,
other => {
return Err(Error::Other(anyhow!(
"unsupported architecture: {other}. Use 'amd64' or 'arm64'."
)));
}
// Resolve target architecture: CLI flag > minimal.toml > host default.
// String-to-arch parsing is delegated to common::target::Arch so the
// alias set stays consistent across every consumer.
let arch: Arch = match args.arch.or(output.arch) {
Some(s) => s
.parse()
.map_err(|e: common::target::ArchParseError| Error::Other(anyhow!("{e}")))?,
None => Target::host().arch().clone(),
};

// OCI images are always Linux
Expand Down