Skip to content

Updating target json support #75

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

Merged
merged 10 commits into from
Jun 2, 2025
Merged
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
11 changes: 9 additions & 2 deletions Cargo.lock

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

5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ exclude = [
resolver = "2"

[workspace.dependencies]
spirv-builder = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "6d7c1cd6c0920500a3fa8c01c23e7b74302c15c4", default-features = false }
spirv-builder = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "86fc48032c4cd4afb74f1d81ae859711d20386a1", default-features = false }
anyhow = "1.0.94"
clap = { version = "4.5.37", features = ["derive"] }
crossterm = "0.28.1"
@@ -29,6 +29,9 @@ test-log = "0.2.16"
cargo_metadata = "0.19.2"
semver = "1.0.26"

# This crate MUST NEVER be upgraded, we need this particular "first" version to support old rust-gpu builds
legacy_target_specs = { package = "rustc_codegen_spirv-target-specs", version = "0.9.0", features = ["include_str"] }

[workspace.lints.rust]
missing_docs = "warn"

1 change: 1 addition & 0 deletions crates/cargo-gpu/Cargo.toml
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ default-run = "cargo-gpu"
cargo_metadata.workspace = true
anyhow.workspace = true
spirv-builder = { workspace = true, features = ["clap", "watch"] }
legacy_target_specs.workspace = true
clap.workspace = true
directories.workspace = true
env_logger.workspace = true
106 changes: 0 additions & 106 deletions crates/cargo-gpu/src/args.rs

This file was deleted.

102 changes: 62 additions & 40 deletions crates/cargo-gpu/src/build.rs
Original file line number Diff line number Diff line change
@@ -2,13 +2,46 @@
#![allow(clippy::unwrap_used, reason = "this is basically a test")]
//! `cargo gpu build`, analogous to `cargo build`
use crate::args::BuildArgs;
use crate::install::Install;
use crate::linkage::Linkage;
use crate::lockfile::LockfileMismatchHandler;
use crate::{install::Install, target_spec_dir};
use anyhow::Context as _;
use spirv_builder::{CompileResult, ModuleResult};
use spirv_builder::{CompileResult, ModuleResult, SpirvBuilder};
use std::io::Write as _;
use std::path::PathBuf;

/// Args for just a build
#[derive(clap::Parser, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct BuildArgs {
/// Path to the output directory for the compiled shaders.
#[clap(long, short, default_value = "./")]
pub output_dir: PathBuf,

/// Watch the shader crate directory and automatically recompile on changes.
#[clap(long, short, action)]
pub watch: bool,

/// the flattened [`SpirvBuilder`]
#[clap(flatten)]
#[serde(flatten)]
pub spirv_builder: SpirvBuilder,

///Renames the manifest.json file to the given name
#[clap(long, short, default_value = "manifest.json")]
pub manifest_file: String,
}

impl Default for BuildArgs {
#[inline]
fn default() -> Self {
Self {
output_dir: PathBuf::from("./"),
watch: false,
spirv_builder: SpirvBuilder::default(),
manifest_file: String::from("manifest.json"),
}
}
}

/// `cargo build` subcommands
#[derive(Clone, clap::Parser, Debug, serde::Deserialize, serde::Serialize)]
@@ -19,54 +52,46 @@ pub struct Build {

/// CLI args for configuring the build of the shader
#[clap(flatten)]
pub build_args: BuildArgs,
pub build: BuildArgs,
}

impl Build {
/// Entrypoint
pub fn run(&mut self) -> anyhow::Result<()> {
let (rustc_codegen_spirv_location, toolchain_channel) = self.install.run()?;
let installed_backend = self.install.run()?;

let _lockfile_mismatch_handler = LockfileMismatchHandler::new(
&self.install.spirv_install.shader_crate,
&toolchain_channel,
self.install
.spirv_install
.force_overwrite_lockfiles_v4_to_v3,
&self.install.shader_crate,
&installed_backend.toolchain_channel,
self.install.force_overwrite_lockfiles_v4_to_v3,
)?;

let builder = &mut self.build_args.spirv_builder;
builder.rustc_codegen_spirv_location = Some(rustc_codegen_spirv_location);
builder.toolchain_overwrite = Some(toolchain_channel);
builder.path_to_crate = Some(self.install.spirv_install.shader_crate.clone());
builder.path_to_target_spec = Some(target_spec_dir()?.join(format!(
"{}.json",
builder.target.as_ref().context("expect target to be set")?
)));
let builder = &mut self.build.spirv_builder;
builder.path_to_crate = Some(self.install.shader_crate.clone());
installed_backend.configure_spirv_builder(builder)?;

// Ensure the shader output dir exists
log::debug!(
"ensuring output-dir '{}' exists",
self.build_args.output_dir.display()
self.build.output_dir.display()
);
std::fs::create_dir_all(&self.build_args.output_dir)?;
let canonicalized = self.build_args.output_dir.canonicalize()?;
log::debug!("canonicalized output dir: {canonicalized:?}");
self.build_args.output_dir = canonicalized;
std::fs::create_dir_all(&self.build.output_dir)?;
let canonicalized = self.build.output_dir.canonicalize()?;
log::debug!("canonicalized output dir: {}", canonicalized.display());
self.build.output_dir = canonicalized;

// Ensure the shader crate exists
self.install.spirv_install.shader_crate =
self.install.spirv_install.shader_crate.canonicalize()?;
self.install.shader_crate = self.install.shader_crate.canonicalize()?;
anyhow::ensure!(
self.install.spirv_install.shader_crate.exists(),
self.install.shader_crate.exists(),
"shader crate '{}' does not exist. (Current dir is '{}')",
self.install.spirv_install.shader_crate.display(),
self.install.shader_crate.display(),
std::env::current_dir()?.display()
);

if self.build_args.watch {
if self.build.watch {
let this = self.clone();
self.build_args
self.build
.spirv_builder
.watch(move |result, accept| {
let result1 = this.parse_compilation_result(&result);
@@ -79,9 +104,9 @@ impl Build {
} else {
crate::user_output!(
"Compiling shaders at {}...\n",
self.install.spirv_install.shader_crate.display()
self.install.shader_crate.display()
);
let result = self.build_args.spirv_builder.build()?;
let result = self.build.spirv_builder.build()?;
self.parse_compilation_result(&result)?;
}
Ok(())
@@ -104,7 +129,7 @@ impl Build {
.into_iter()
.map(|(entry, filepath)| -> anyhow::Result<Linkage> {
use relative_path::PathExt as _;
let path = self.build_args.output_dir.join(
let path = self.build.output_dir.join(
filepath
.file_name()
.context("Couldn't parse file name from shader module path")?,
@@ -114,10 +139,10 @@ impl Build {
log::debug!(
"linkage of {} relative to {}",
path.display(),
self.install.spirv_install.shader_crate.display()
self.install.shader_crate.display()
);
let spv_path = path
.relative_to(&self.install.spirv_install.shader_crate)
.relative_to(&self.install.shader_crate)
.map_or(path, |path_relative_to_shader_crate| {
path_relative_to_shader_crate.to_path("")
});
@@ -128,10 +153,7 @@ impl Build {
linkage.sort();

// Write the shader manifest json file
let manifest_path = self
.build_args
.output_dir
.join(&self.build_args.manifest_file);
let manifest_path = self.build.output_dir.join(&self.build.manifest_file);
let json = serde_json::to_string_pretty(&linkage)?;
let mut file = std::fs::File::create(&manifest_path).with_context(|| {
format!(
@@ -176,8 +198,8 @@ mod test {
command: Command::Build(build),
} = Cli::parse_from(args)
{
assert_eq!(shader_crate_path, build.install.spirv_install.shader_crate);
assert_eq!(output_dir, build.build_args.output_dir);
assert_eq!(shader_crate_path, build.install.shader_crate);
assert_eq!(output_dir, build.build.output_dir);

// TODO:
// For some reason running a full build (`build.run()`) inside tests fails on Windows.
75 changes: 14 additions & 61 deletions crates/cargo-gpu/src/config.rs
Original file line number Diff line number Diff line change
@@ -14,28 +14,9 @@ impl Config {

/// Convert CLI args to their serde JSON representation.
fn cli_args_to_json(env_args: Vec<String>) -> anyhow::Result<serde_json::Value> {
let mut cli_args_json = serde_json::to_value(crate::build::Build::parse_from(env_args))?;

// Move `/install/spirv_install` to `/install`
let spirv_install = cli_args_json
.pointer("/install/spirv_install")
.context("`/install/spirv_install` not found in config")?
.clone();
*cli_args_json
.get_mut("install")
.context("`/install` not found in config")? = spirv_install;

let build = cli_args_json
.pointer("/build_args")
.context("`/build_args` not found in config")?
.clone();

// Move `/build_args` to `/build`
let object = cli_args_json.as_object_mut().context("!")?;
object.remove("build_args");
object.insert("build".to_owned(), build);

Ok(cli_args_json)
Ok(serde_json::to_value(crate::build::Build::parse_from(
Copy link
Collaborator

Choose a reason for hiding this comment

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

Niiiice, so much simpler 🚀

Copy link
Member Author

Choose a reason for hiding this comment

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

these are some of the commits I cherry-picked from my library refactor :D

Copy link
Collaborator

Choose a reason for hiding this comment

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

oooh :D

env_args,
))?)
}

/// Config for the `cargo gpu build` and `cargo gpu install` can be set in the shader crate's
@@ -47,30 +28,11 @@ impl Config {
) -> anyhow::Result<crate::build::Build> {
let mut config = crate::metadata::Metadata::as_json(shader_crate_path)?;

env_args = env_args
.into_iter()
.filter(|arg| !(arg == "build" || arg == "install"))
.collect::<Vec<_>>();
env_args.retain(|arg| !(arg == "build" || arg == "install"));
let cli_args_json = Self::cli_args_to_json(env_args)?;

Self::json_merge(&mut config, cli_args_json, None)?;

let build = config
.get("build")
.context("`build` not found in merged configs")?
.clone();

let install = config
.get("install")
.context("`install` not found in merged configs")?
.clone();

let args = serde_json::from_value::<crate::build::Build>(serde_json::json!({
"build_args": build,
"install": {
"spirv_install": install
}
}))?;
let args = serde_json::from_value::<crate::build::Build>(config)?;
Ok(args)
}

@@ -140,8 +102,8 @@ mod test {
],
)
.unwrap();
assert!(!args.build_args.spirv_builder.release);
assert!(args.install.spirv_install.auto_install_rust_toolchain);
assert!(!args.build.spirv_builder.release);
assert!(args.install.auto_install_rust_toolchain);
}

#[test_log::test]
@@ -161,8 +123,8 @@ mod test {
.unwrap();

let args = Config::clap_command_with_cargo_config(&shader_crate_path, vec![]).unwrap();
assert!(!args.build_args.spirv_builder.release);
assert!(args.install.spirv_install.auto_install_rust_toolchain);
assert!(!args.build.spirv_builder.release);
assert!(args.install.auto_install_rust_toolchain);
}

fn update_cargo_output_dir() -> std::path::PathBuf {
@@ -186,15 +148,9 @@ mod test {

let args = Config::clap_command_with_cargo_config(&shader_crate_path, vec![]).unwrap();
if cfg!(target_os = "windows") {
assert_eq!(
args.build_args.output_dir,
std::path::Path::new("C:/the/moon")
);
assert_eq!(args.build.output_dir, std::path::Path::new("C:/the/moon"));
} else {
assert_eq!(
args.build_args.output_dir,
std::path::Path::new("/the/moon")
);
assert_eq!(args.build.output_dir, std::path::Path::new("/the/moon"));
}
}

@@ -212,10 +168,7 @@ mod test {
],
)
.unwrap();
assert_eq!(
args.build_args.output_dir,
std::path::Path::new("/the/river")
);
assert_eq!(args.build.output_dir, std::path::Path::new("/the/river"));
}

#[test_log::test]
@@ -234,7 +187,7 @@ mod test {

let args = Config::clap_command_with_cargo_config(&shader_crate_path, vec![]).unwrap();
assert_eq!(
args.build_args.spirv_builder.capabilities,
args.build.spirv_builder.capabilities,
vec![
spirv_builder::Capability::AtomicStorage,
spirv_builder::Capability::Matrix
@@ -256,6 +209,6 @@ mod test {
],
)
.unwrap();
assert_eq!(args.build_args.manifest_file, "mymanifest".to_owned());
assert_eq!(args.build.manifest_file, "mymanifest".to_owned());
}
}
269 changes: 213 additions & 56 deletions crates/cargo-gpu/src/install.rs

Large diffs are not rendered by default.

26 changes: 26 additions & 0 deletions crates/cargo-gpu/src/legacy_target_specs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Legacy target specs are spec jsons for versions before `rustc_codegen_spirv-target-specs`
//! came bundled with them. Instead, cargo gpu needs to bundle these legacy spec files. Luckily,
//! they are the same for all versions, as bundling target specs with the codegen backend was
//! introduced before the first target spec update.
use anyhow::Context as _;
use log::info;
use std::path::Path;

/// Extract legacy target specs from our executable into some directory
pub fn write_legacy_target_specs(target_spec_dir: &Path, rebuild: bool) -> anyhow::Result<()> {
info!(
"Writing legacy target specs to {}",
target_spec_dir.display()
);
std::fs::create_dir_all(target_spec_dir)?;
for (filename, contents) in legacy_target_specs::TARGET_SPECS {
let path = target_spec_dir.join(filename);
if !path.is_file() || rebuild {
std::fs::write(&path, contents.as_bytes()).with_context(|| {
format!("writing legacy target spec file at [{}]", path.display())
})?;
}
}
Ok(())
}
21 changes: 7 additions & 14 deletions crates/cargo-gpu/src/main.rs
Original file line number Diff line number Diff line change
@@ -55,11 +55,11 @@ use clap::Parser as _;
use install::Install;
use show::Show;

mod args;
mod build;
mod config;
mod install;
mod install_toolchain;
mod legacy_target_specs;
mod linkage;
mod lockfile;
mod metadata;
@@ -128,8 +128,8 @@ fn run() -> anyhow::Result<()> {

match cli.command {
Command::Install(install) => {
let shader_crate_path = install.spirv_install.shader_crate;
let mut command =
let shader_crate_path = install.shader_crate;
let command =
config::Config::clap_command_with_cargo_config(&shader_crate_path, env_args)?;
log::debug!(
"installing with final merged arguments: {:#?}",
@@ -138,16 +138,16 @@ fn run() -> anyhow::Result<()> {
command.install.run()?;
}
Command::Build(build) => {
let shader_crate_path = build.install.spirv_install.shader_crate;
let shader_crate_path = build.install.shader_crate;
let mut command =
config::Config::clap_command_with_cargo_config(&shader_crate_path, env_args)?;
log::debug!("building with final merged arguments: {command:#?}");

if command.build_args.watch {
if command.build.watch {
// When watching, do one normal run to setup the `manifest.json` file.
command.build_args.watch = false;
command.build.watch = false;
command.run()?;
command.build_args.watch = true;
command.build.watch = true;
command.run()?;
} else {
command.run()?;
@@ -202,13 +202,6 @@ fn cache_dir() -> anyhow::Result<std::path::PathBuf> {
})
}

/// Location of the target spec metadata files
fn target_spec_dir() -> anyhow::Result<std::path::PathBuf> {
let dir = cache_dir()?.join("target-specs");
std::fs::create_dir_all(&dir)?;
Ok(dir)
}

/// Convenience function for internal use. Dumps all the CLI usage instructions. Useful for
/// updating the README.
fn dump_full_usage_for_readme() -> anyhow::Result<()> {
83 changes: 42 additions & 41 deletions crates/cargo-gpu/src/spirv_source.rs
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@
use anyhow::Context as _;
use cargo_metadata::camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::semver::Version;
use cargo_metadata::{MetadataCommand, Package};
use cargo_metadata::{Metadata, MetadataCommand, Package};
use std::fs;
use std::path::{Path, PathBuf};

@@ -96,8 +96,9 @@ impl SpirvSource {

/// Look into the shader crate to get the version of `rust-gpu` it's using.
pub fn get_rust_gpu_deps_from_shader(shader_crate_path: &Path) -> anyhow::Result<Self> {
let spirv_std_package = get_package_from_crate(shader_crate_path, "spirv-std")?;
let spirv_source = Self::parse_spirv_std_source_and_version(&spirv_std_package)?;
let crate_metadata = query_metadata(shader_crate_path)?;
let spirv_std_package = crate_metadata.find_package("spirv-std")?;
let spirv_source = Self::parse_spirv_std_source_and_version(spirv_std_package)?;
log::debug!(
"Parsed `SpirvSource` from crate `{}`: \
{spirv_source:?}",
@@ -121,6 +122,11 @@ impl SpirvSource {
}
}

/// Returns true if self is a Path
pub const fn is_path(&self) -> bool {
matches!(self, Self::Path { .. })
}

/// Parse a string like:
/// `spirv-std v0.9.0 (https://github.com/Rust-GPU/rust-gpu?rev=54f6978c#54f6978c) (*)`
/// Which would return:
@@ -175,46 +181,41 @@ impl SpirvSource {
}
}

/// Make sure shader crate path is absolute and canonical.
fn crate_path_canonical(shader_crate_path: &Path) -> anyhow::Result<PathBuf> {
let mut canonical_path = shader_crate_path.to_path_buf();

if !canonical_path.is_absolute() {
let cwd = std::env::current_dir().context("no cwd")?;
canonical_path = cwd.join(canonical_path);
}
canonical_path = canonical_path
.canonicalize()
.context("could not get absolute path to shader crate")?;

if !canonical_path.is_dir() {
log::error!("{shader_crate_path:?} is not a directory, aborting");
anyhow::bail!("{shader_crate_path:?} is not a directory");
}
Ok(canonical_path)
}

/// get the Package metadata from some crate
pub fn get_package_from_crate(crate_path: &Path, crate_name: &str) -> anyhow::Result<Package> {
let canonical_crate_path = crate_path_canonical(crate_path)?;

log::debug!(
"Running `cargo metadata` on `{}` to query for package `{crate_name}`",
canonical_crate_path.display()
);
pub fn query_metadata(crate_path: &Path) -> anyhow::Result<Metadata> {
log::debug!("Running `cargo metadata` on `{}`", crate_path.display());
let metadata = MetadataCommand::new()
.current_dir(&canonical_crate_path)
.current_dir(
&crate_path
.canonicalize()
.context("could not get absolute path to shader crate")?,
)
.exec()?;
Ok(metadata)
}

/// implements [`Self::find_package`]
pub trait FindPackage {
/// Search for a package or return a nice error
fn find_package(&self, crate_name: &str) -> anyhow::Result<&Package>;
}

let Some(package) = metadata
.packages
.into_iter()
.find(|package| package.name.eq(crate_name))
else {
anyhow::bail!("`{crate_name}` not found in `Cargo.toml` at `{canonical_crate_path:?}`");
};
log::trace!(" found `{}` version `{}`", package.name, package.version);
Ok(package)
impl FindPackage for Metadata {
fn find_package(&self, crate_name: &str) -> anyhow::Result<&Package> {
if let Some(package) = self
.packages
.iter()
.find(|package| package.name.eq(crate_name))
{
log::trace!(" found `{}` version `{}`", package.name, package.version);
Ok(package)
} else {
anyhow::bail!(
"`{crate_name}` not found in `Cargo.toml` at `{:?}`",
self.workspace_root
);
}
}
}

/// Parse the `rust-toolchain.toml` in the working tree of the checked-out version of the `rust-gpu` repo.
@@ -252,7 +253,7 @@ mod test {
source,
SpirvSource::Git {
url: "https://github.com/Rust-GPU/rust-gpu".to_owned(),
rev: "82a0f69008414f51d59184763146caa6850ac588".to_owned()
rev: "86fc48032c4cd4afb74f1d81ae859711d20386a1".to_owned()
}
);
}
@@ -274,6 +275,6 @@ mod test {
.to_str()
.map(std::string::ToString::to_string)
.unwrap();
assert_eq!("https___github_com_Rust-GPU_rust-gpu+82a0f690", &name);
assert_eq!("https___github_com_Rust-GPU_rust-gpu+86fc4803", &name);
}
}
9 changes: 5 additions & 4 deletions crates/shader-crate-template/Cargo.lock
2 changes: 1 addition & 1 deletion crates/shader-crate-template/Cargo.toml
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ crate-type = ["rlib", "cdylib"]
# Dependencies for CPU and GPU code
[dependencies]
# TODO: use a simple crate version once v0.10.0 is released
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu", rev = "82a0f69" }
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu", rev = "86fc48032c4cd4afb74f1d81ae859711d20386a1" }

# Dependencies for GPU code
[target.'cfg(target_arch = "spirv")'.dependencies]