Skip to content

Commit

Permalink
Rely on clap default values instead of Option (#673)
Browse files Browse the repository at this point in the history
  • Loading branch information
ia0 authored Nov 7, 2024
1 parent 1ce41e3 commit e4eb022
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 29 deletions.
8 changes: 7 additions & 1 deletion crates/cli-tools/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@

### Major

- Remove `Option` from `action::RustAppletBuild::profile`
- Remove `dir` argument from `action::RustApplet{Build,Test}::run()` (replaced with the `crate_dir`
field)
- Rename `action::RustAppletBuild::output` to `output_dir`, remove `Option`, and change default
value from `target/wasefire` to `wasefire`
- Change `action::{Transfer,RustApplet{New,Build,Test}}` to consume `self`
- Remove `Default` for `action::RustAppletBuild` (implement `clap::Parser` instead)
- Add `action` feature to gate the `action` module
- Change API to be async using tokio

### Minor

- Add `action::RustApplet{Build,Test}::crate_dir`
- Add `action::PlatformInfo` to print platform serial and version
- Add `cmd::spawn()` for more control on command execution
- Add `fs::remove_dir_all()` to remove a directory recursively
Expand Down Expand Up @@ -40,4 +46,4 @@

## 0.1.0

<!-- Increment to skip CHANGELOG.md test: 8 -->
<!-- Increment to skip CHANGELOG.md test: 9 -->
42 changes: 25 additions & 17 deletions crates/cli-tools/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,13 +490,19 @@ pub struct RustAppletBuild {
#[arg(long, value_name = "TARGET")]
pub native: Option<String>,

/// Copies the final artifacts to this directory instead of target/wasefire.
#[arg(long, value_name = "DIR", value_hint = ValueHint::DirPath)]
pub output: Option<PathBuf>,
/// Root directory of the crate.
#[arg(long, value_name = "DIRECTORY", default_value = ".")]
#[arg(value_hint = ValueHint::DirPath)]
pub crate_dir: PathBuf,

/// Cargo profile, defaults to release.
#[arg(long)]
pub profile: Option<String>,
/// Copies the final artifacts to this directory.
#[arg(long, value_name = "DIRECTORY", default_value = "wasefire")]
#[arg(value_hint = ValueHint::DirPath)]
pub output_dir: PathBuf,

/// Cargo profile.
#[arg(long, default_value = "release")]
pub profile: String,

/// Optimization level.
#[clap(long, short = 'O')]
Expand All @@ -512,8 +518,8 @@ pub struct RustAppletBuild {
}

impl RustAppletBuild {
pub async fn run(self, dir: impl AsRef<Path>) -> Result<()> {
let metadata = metadata(dir.as_ref()).await?;
pub async fn run(self) -> Result<()> {
let metadata = metadata(&self.crate_dir).await?;
let package = &metadata.packages[0];
let target_dir =
fs::try_relative(std::env::current_dir()?, &metadata.target_directory).await?;
Expand All @@ -538,7 +544,7 @@ impl RustAppletBuild {
wasefire_feature(package, "native", &mut cargo)?;
}
}
let profile = self.profile.as_deref().unwrap_or("release");
let profile = &self.profile;
cargo.arg(format!("--profile={profile}"));
if let Some(level) = self.opt_level {
cargo.arg(format!("--config=profile.{profile}.opt-level={level}"));
Expand All @@ -555,17 +561,13 @@ impl RustAppletBuild {
cargo.env("WASEFIRE_DEBUG", "");
}
cargo.env("RUSTFLAGS", rustflags.join(" "));
cargo.current_dir(dir);
cargo.current_dir(&self.crate_dir);
cmd::execute(&mut cargo).await?;
let out_dir = match &self.output {
Some(x) => x.clone(),
None => "target/wasefire".into(),
};
let (src, dst) = match &self.native {
None => (format!("wasm32-unknown-unknown/{profile}/{name}.wasm"), "applet.wasm"),
Some(target) => (format!("{target}/{profile}/lib{name}.a"), "libapplet.a"),
};
let applet = out_dir.join(dst);
let applet = self.output_dir.join(dst);
if fs::copy_if_changed(target_dir.join(src), &applet).await? && dst.ends_with(".wasm") {
optimize_wasm(&applet, self.opt_level).await?;
}
Expand All @@ -576,19 +578,25 @@ impl RustAppletBuild {
/// Runs the unit-tests of a Rust applet project.
#[derive(clap::Args)]
pub struct RustAppletTest {
/// Root directory of the crate.
#[arg(long, value_name = "DIRECTORY", default_value = ".")]
#[arg(value_hint = ValueHint::DirPath)]
crate_dir: PathBuf,

/// Extra arguments to cargo, e.g. --features=foo.
#[clap(last = true)]
cargo: Vec<String>,
}

impl RustAppletTest {
pub async fn run(self, dir: impl AsRef<Path>) -> Result<()> {
let metadata = metadata(dir.as_ref()).await?;
pub async fn run(self) -> Result<()> {
let metadata = metadata(&self.crate_dir).await?;
let package = &metadata.packages[0];
ensure!(package.features.contains_key("test"), "missing test feature");
let mut cargo = Command::new("cargo");
cargo.args(["test", "--features=test"]);
cargo.args(&self.cargo);
cargo.current_dir(&self.crate_dir);
cmd::replace(cargo)
}
}
Expand Down
9 changes: 7 additions & 2 deletions crates/cli-tools/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,13 @@ pub async fn copy_if_changed(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Re
changed = src_data != dst_data;
}
if changed {
copy(&src, dst).await?;
tokio::fs::copy(src, dst_orig).await?;
if exists(&dst_orig).await {
tokio::fs::remove_file(&dst_orig).await?;
} else if let Some(parent) = dst.as_ref().parent() {
create_dir_all(parent).await?;
}
copy(&src, &dst).await?;
tokio::fs::copy(&src, &dst_orig).await?;
}
Ok(changed)
}
Expand Down
2 changes: 2 additions & 0 deletions crates/cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

### Major

- Rename `--output` to `--output-dir` for `rust-applet-build`
- Rename `--serial` to `--protocol` with more support
- Move `--serial` and `--timeout` to commands that need them

### Minor

- Add `--crate-dir` for `rust-applet-{build,test}`
- Add `platform-info` to print platform serial and version
- Add `host` to start a host platform
- Support `RUST_LOG` to control logging
Expand Down
5 changes: 2 additions & 3 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,6 @@ impl Completion {
async fn main() -> Result<()> {
env_logger::init();
let flags = Flags::parse();
let dir = std::env::current_dir()?;
match flags.action {
Action::AppletList => bail!("not implemented yet"),
Action::AppletInstall { options, action, command } => {
Expand Down Expand Up @@ -283,8 +282,8 @@ async fn main() -> Result<()> {
Action::PlatformLock { options, action } => action.run(&mut options.connect().await?).await,
Action::PlatformRpc { options, action } => action.run(&mut options.connect().await?).await,
Action::RustAppletNew(x) => x.run().await,
Action::RustAppletBuild(x) => x.run(dir).await,
Action::RustAppletTest(x) => x.run(dir).await,
Action::RustAppletBuild(x) => x.run().await,
Action::RustAppletTest(x) => x.run().await,
Action::Completion(x) => x.run().await,
}
}
17 changes: 11 additions & 6 deletions crates/xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;

Expand Down Expand Up @@ -336,12 +337,12 @@ impl AppletOptions {
}

async fn execute_rust(self, main: &MainOptions, command: &Option<AppletCommand>) -> Result<()> {
let dir = if self.name.starts_with(['.', '/']) {
self.name.clone()
let dir: PathBuf = if self.name.starts_with(['.', '/']) {
self.name.into()
} else {
format!("examples/{}/{}", self.lang, self.name)
["examples", &self.lang, &self.name].into_iter().collect()
};
ensure!(fs::exists(&dir).await, "{dir} does not exist");
ensure!(fs::exists(&dir).await, "{} does not exist", dir.display());
let native = match (main.native, &main.native_target, command) {
(_, Some(target), command) => {
if let Some(AppletCommand::Runner(x)) = command {
Expand All @@ -359,15 +360,19 @@ impl AppletOptions {
let mut action = action::RustAppletBuild {
prod: main.release,
native: native.map(|x| x.to_string()),
profile: self.profile.clone(),
opt_level: self.opt_level,
stack_size: self.stack_size,
crate_dir: dir,
output_dir: "target/wasefire".into(),
..action::RustAppletBuild::parse_from::<_, OsString>([])
};
if let Some(profile) = self.profile {
action.profile = profile;
}
for features in &self.features {
action.cargo.push(format!("--features={features}"));
}
action.run(dir).await?;
action.run().await?;
if !main.size && main.footprint.is_none() {
return Ok(());
}
Expand Down

0 comments on commit e4eb022

Please sign in to comment.