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

Rename WasiState::new() to WasiState::builder() #3471

Merged
merged 4 commits into from
Jan 16, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
6 changes: 3 additions & 3 deletions docs/migration_to_3.0.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub struct MyEnv {
pub memory: wasmer::LazyInit<Memory>,
#[wasmer(export(name = "__alloc"))]
pub alloc_guest_memory: LazyInit<NativeFunc<u32, i32>>,

pub multiply_by: u32,
}

Expand Down Expand Up @@ -153,7 +153,7 @@ let str = ptr.read_utf8_string(&memory_view, length as u32).unwrap();
println!("Memory contents: {:?}", str);
```

The reason for this change is that in the future this will enable
The reason for this change is that in the future this will enable
safely sharing memory across threads. The same thing goes for reading slices:

```rust
Expand Down Expand Up @@ -199,7 +199,7 @@ let instance = Instance::new(&mut store, &module, &import_object).expect("Could
For WASI, don't forget to initialize the `WasiEnv` (it will import the memory)

```rust
let mut wasi_env = WasiState::new("hello").finalize()?;
let mut wasi_env = WasiState::builder("hello").finalize()?;
let import_object = wasi_env.import_object(&mut store, &module)?;
let instance = Instance::new(&mut store, &module, &import_object).expect("Could not instantiate module.");
wasi_env.initialize(&mut store, &instance).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion examples/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

println!("Creating `WasiEnv`...");
// First, we create the `WasiEnv`
let mut wasi_env = WasiState::new("hello")
let mut wasi_env = WasiState::builder("hello")
// .args(&["world"])
// .env("KEY", "Value")
.finalize(&mut store)?;
Expand Down
2 changes: 1 addition & 1 deletion examples/wasi_pipes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// First, we create the `WasiEnv` with the stdio pipes
let mut input = Pipe::new();
let mut output = Pipe::new();
let wasi_env = WasiState::new("hello")
let wasi_env = WasiState::builder("hello")
.stdin(Box::new(input.clone()))
.stdout(Box::new(output.clone()))
.finalize(&mut store)?;
Expand Down
2 changes: 1 addition & 1 deletion lib/c-api/src/wasm_c_api/wasi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub unsafe extern "C" fn wasi_config_new(
inherit_stdout: true,
inherit_stderr: true,
inherit_stdin: true,
state_builder: WasiState::new(prog_name),
state_builder: WasiState::builder(prog_name),
}))
}

Expand Down
2 changes: 1 addition & 1 deletion lib/cli/src/commands/run/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl Wasi {

let runtime = Arc::new(PluggableRuntimeImplementation::default());

let mut wasi_state_builder = WasiState::new(program_name);
let mut wasi_state_builder = WasiState::builder(program_name);
wasi_state_builder
.args(args)
.envs(self.env_vars.clone())
Expand Down
10 changes: 5 additions & 5 deletions lib/wasi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ WASI easily from the Wasmer runtime, through our `ImportObject` API.

## Supported WASI versions

| WASI version | Support |
|-|-|
| `wasi_unstable` | ✅ |
| `wasi_snapshot_preview1` | ✅ |
| WASI version | Support |
| ------------------------ | ------- |
| `wasi_unstable` | ✅ |
| `wasi_snapshot_preview1` | ✅ |

The special `Latest` version points to `wasi_snapshot_preview1`.

Expand Down Expand Up @@ -67,7 +67,7 @@ let mut store = Store::default();
let module = Module::from_file(&store, "hello.wasm")?;

// Create the `WasiEnv`.
let wasi_env = WasiState::new("command-name")
let wasi_env = WasiState::builder("command-name")
.args(&["Gordon"])
.finalize()?;

Expand Down
2 changes: 1 addition & 1 deletion lib/wasi/src/os/console/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ impl Console {
let wasi_thread = wasi_process.new_thread();

// Create the state
let mut state = WasiState::new(prog);
let mut state = WasiState::builder(prog);
if let Some(stdin) = self.stdin.take() {
state.stdin(Box::new(stdin));
}
Expand Down
2 changes: 1 addition & 1 deletion lib/wasi/src/runners/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ fn prepare_webc_env(
.collect::<Vec<_>>();

let filesystem = Box::new(WebcFileSystem::init(webc, &package_name));
let mut wasi_env = WasiState::new(command);
let mut wasi_env = WasiState::builder(command);
wasi_env.set_fs(filesystem);
wasi_env.args(args);
for f_name in top_level_dirs.iter() {
Expand Down
34 changes: 16 additions & 18 deletions lib/wasi/src/state/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,13 @@ use crate::{
PluggableRuntimeImplementation, WasiEnv, WasiFunctionEnv,
};

/// Creates an empty [`WasiStateBuilder`].
///
/// Internal method only, users should call [`WasiState::new`].
pub(crate) fn create_wasi_state(program_name: &str) -> WasiStateBuilder {
WasiStateBuilder {
args: vec![program_name.to_string()],
..WasiStateBuilder::default()
}
}

/// Convenient builder API for configuring WASI via [`WasiState`].
///
/// Usage:
/// ```no_run
/// # use wasmer_wasi::{WasiState, WasiStateCreationError};
/// # fn main() -> Result<(), WasiStateCreationError> {
/// let mut state_builder = WasiState::new("wasi-prog-name");
/// let mut state_builder = WasiState::builder("wasi-prog-name");
/// state_builder
/// .env("ENV_VAR", "ENV_VAL")
/// .arg("--verbose")
Expand Down Expand Up @@ -122,6 +112,14 @@ pub type SetupFsFn = Box<dyn Fn(&mut WasiInodes, &mut WasiFs) -> Result<(), Stri
// TODO add other WasiFS APIs here like swapping out stdout, for example (though we need to
// return stdout somehow, it's unclear what that API should look like)
impl WasiStateBuilder {
/// Creates an empty [`WasiStateBuilder`].
pub(crate) fn new(program_name: &str) -> Self {
WasiStateBuilder {
args: vec![program_name.to_string()],
..WasiStateBuilder::default()
}
}

/// Add an environment variable pair.
///
/// Both the key and value of an environment variable must not
Expand Down Expand Up @@ -263,7 +261,7 @@ impl WasiStateBuilder {
/// ```no_run
/// # use wasmer_wasi::{WasiState, WasiStateCreationError};
/// # fn main() -> Result<(), WasiStateCreationError> {
/// WasiState::new("program_name")
/// WasiState::builder("program_name")
/// .preopen(|p| p.directory("src").read(true).write(true).create(true))?
/// .preopen(|p| p.directory(".").alias("dot").read(true))?
/// .build()?;
Expand Down Expand Up @@ -747,7 +745,7 @@ mod test {
fn env_var_errors() {
// `=` in the key is invalid.
assert!(
create_wasi_state("test_prog")
WasiStateBuilder::new("test_prog")
.env("HOM=E", "/home/home")
.build()
.is_err(),
Expand All @@ -756,7 +754,7 @@ mod test {

// `\0` in the key is invalid.
assert!(
create_wasi_state("test_prog")
WasiStateBuilder::new("test_prog")
.env("HOME\0", "/home/home")
.build()
.is_err(),
Expand All @@ -765,7 +763,7 @@ mod test {

// `=` in the value is valid.
assert!(
create_wasi_state("test_prog")
WasiStateBuilder::new("test_prog")
.env("HOME", "/home/home=home")
.build()
.is_ok(),
Expand All @@ -774,7 +772,7 @@ mod test {

// `\0` in the value is invalid.
assert!(
create_wasi_state("test_prog")
WasiStateBuilder::new("test_prog")
.env("HOME", "/home/home\0")
.build()
.is_err(),
Expand All @@ -784,12 +782,12 @@ mod test {

#[test]
fn nul_character_in_args() {
let output = create_wasi_state("test_prog").arg("--h\0elp").build();
let output = WasiStateBuilder::new("test_prog").arg("--h\0elp").build();
match output {
Err(WasiStateCreationError::ArgumentContainsNulByte(_)) => assert!(true),
_ => assert!(false),
}
let output = create_wasi_state("test_prog")
let output = WasiStateBuilder::new("test_prog")
.args(&["--help", "--wat\0"])
.build();
match output {
Expand Down
11 changes: 9 additions & 2 deletions lib/wasi/src/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ impl WasiBusState {
/// ```no_run
/// # use wasmer_wasi::{WasiState, WasiStateCreationError};
/// # fn main() -> Result<(), WasiStateCreationError> {
/// WasiState::new("program_name")
/// WasiState::builder("program_name")
/// .env(b"HOME", "/home/home".to_string())
/// .arg("--help")
/// .envs({
Expand Down Expand Up @@ -264,8 +264,15 @@ impl WasiState {
/// Create a [`WasiStateBuilder`] to construct a validated instance of
/// [`WasiState`].
#[allow(clippy::new_ret_no_self)]
#[deprecated(note = "Use WasiState::builder()", since = "3.2.0")]
pub fn new(program_name: impl AsRef<str>) -> WasiStateBuilder {
create_wasi_state(program_name.as_ref())
WasiState::builder(program_name)
}

/// Create a [`WasiStateBuilder`] to construct a validated instance of
/// [`WasiState`].
pub fn builder(program_name: impl AsRef<str>) -> WasiStateBuilder {
WasiStateBuilder::new(program_name.as_ref())
}

/// Turn the WasiState into bytes
Expand Down
2 changes: 1 addition & 1 deletion lib/wasi/tests/catsay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async fn test_catsay() {
async fn run_test(mut store: Store, module: Module) {
// Create the `WasiEnv`.
let mut stdout = Pipe::default();
let mut wasi_state_builder = WasiState::new("catsay");
let mut wasi_state_builder = WasiState::builder("catsay");

let mut stdin_pipe = Pipe::default();

Expand Down
2 changes: 1 addition & 1 deletion lib/wasi/tests/condvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ async fn test_condvar() {
async fn run_test(mut store: Store, module: Module) {
// Create the `WasiEnv`.
let mut stdout = Pipe::default();
let mut wasi_state_builder = WasiState::new("multi-threading");
let mut wasi_state_builder = WasiState::builder("multi-threading");

let mut wasi_env = wasi_state_builder
.stdout(Box::new(stdout.clone()))
Expand Down
2 changes: 1 addition & 1 deletion lib/wasi/tests/coreutils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ async fn test_coreutils() {
async fn run_test(mut store: Store, module: Module) {
// Create the `WasiEnv`.
let mut stdout = Pipe::default();
let mut wasi_state_builder = WasiState::new("echo");
let mut wasi_state_builder = WasiState::builder("echo");
wasi_state_builder.args(&["apple"]);

let mut wasi_env = wasi_state_builder
Expand Down
2 changes: 1 addition & 1 deletion lib/wasi/tests/multi-threading.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async fn test_multithreading() {
async fn run_test(mut store: Store, module: Module) {
// Create the `WasiEnv`.
let mut stdout = Pipe::default();
let mut wasi_state_builder = WasiState::new("multi-threading");
let mut wasi_state_builder = WasiState::builder("multi-threading");

let mut wasi_env = wasi_state_builder
.stdout(Box::new(stdout.clone()))
Expand Down
6 changes: 3 additions & 3 deletions lib/wasi/tests/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async fn test_stdout() {
let mut pipe = WasiBidirectionalSharedPipePair::default();
// FIXME: evaluate if needed (method not available on ArcFile)
// pipe.set_blocking(false);
let mut wasi_env = WasiState::new("command-name")
let mut wasi_env = WasiState::builder("command-name")
.args(&["Gordon"])
.stdout(Box::new(pipe.clone()))
.finalize(&mut store)
Expand Down Expand Up @@ -116,7 +116,7 @@ async fn test_env() {
let mut pipe = WasiBidirectionalSharedPipePair::default();
// FIXME: evaluate if needed (method not available)
// .with_blocking(false);
let mut wasi_state_builder = WasiState::new("command-name");
let mut wasi_state_builder = WasiState::builder("command-name");
wasi_state_builder
.args(&["Gordon"])
.env("DOG", "X")
Expand Down Expand Up @@ -164,7 +164,7 @@ async fn test_stdin() {
let buf = "Hello, stdin!\n".as_bytes().to_owned();
pipe.write(&buf[..]).await.unwrap();

let mut wasi_env = WasiState::new("command-name")
let mut wasi_env = WasiState::builder("command-name")
.stdin(Box::new(pipe.clone()))
.finalize(&mut store)
.unwrap();
Expand Down
2 changes: 1 addition & 1 deletion tests/lib/wast/src/wasi_wast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ impl<'a> WasiTest<'a> {
mpsc::Receiver<Vec<u8>>,
mpsc::Receiver<Vec<u8>>,
)> {
let mut builder = WasiState::new(self.wasm_path);
let mut builder = WasiState::builder(self.wasm_path);

let stdin_pipe = WasiBidirectionalPipePair::new().with_blocking(false);
builder.stdin(Box::new(stdin_pipe));
Expand Down