Skip to content

Commit

Permalink
Merge pull request #4013 from wasmerio/wasmer-dir
Browse files Browse the repository at this point in the history
Added a WasmerDir abstraction to the CLI
  • Loading branch information
Michael Bryan authored Jun 21, 2023
2 parents 01de45d + 52eed73 commit e96e7b4
Show file tree
Hide file tree
Showing 14 changed files with 345 additions and 246 deletions.
17 changes: 9 additions & 8 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion lib/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ wasmer-wasix-experimental-io-devices = { version = "0.8.0", path = "../wasi-expe
wasmer-wast = { version = "=4.0.0-beta.3", path = "../../tests/lib/wast", optional = true }
wasmer-cache = { version = "=4.0.0-beta.3", path = "../cache", features = ["blake3-pure"] }
wasmer-types = { version = "=4.0.0-beta.3", path = "../types", features = ["enable-serde"] }
wasmer-registry = { version = "5.1.0", path = "../registry", features = ["build-package"] }
wasmer-registry = { version = "5.1.0", path = "../registry", features = ["build-package", "clap"] }
wasmer-object = { version = "=4.0.0-beta.3", path = "../object", optional = true }
virtual-fs = { version = "0.6.0", path = "../virtual-fs", default-features = false, features = ["host-fs"] }
virtual-net = { version = "0.3.0", path = "../virtual-net" }
Expand Down
26 changes: 6 additions & 20 deletions lib/cli/src/commands/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ use std::process::{Command, Stdio};

use anyhow::{Context, Error};
use clap::Parser;
use wasmer_registry::{Bindings, ProgrammingLanguage, WasmerConfig};
use wasmer_registry::{wasmer_env::WasmerEnv, Bindings, ProgrammingLanguage};

/// Add a Wasmer package's bindings to your application.
#[derive(Debug, Parser)]
pub struct Add {
/// The registry to fetch bindings from.
#[clap(long, env = "WASMER_REGISTRY")]
registry: Option<String>,
#[clap(flatten)]
env: WasmerEnv,
/// Add the JavaScript bindings using "npm install".
#[clap(long, groups = &["bindings", "js"])]
npm: bool,
Expand All @@ -32,10 +31,11 @@ impl Add {
anyhow::ensure!(!self.packages.is_empty(), "No packages specified");

let registry = self
.registry()
.env
.registry_endpoint()
.context("Unable to determine which registry to use")?;

let bindings = self.lookup_bindings(&registry)?;
let bindings = self.lookup_bindings(registry.as_str())?;

let mut cmd = self.target()?.command(&bindings)?;
cmd.stdin(Stdio::null())
Expand Down Expand Up @@ -71,20 +71,6 @@ impl Add {
Ok(bindings_to_add)
}

fn registry(&self) -> Result<String, Error> {
match &self.registry {
Some(r) => Ok(r.clone()),
None => {
let wasmer_dir =
WasmerConfig::get_wasmer_dir().map_err(|e| anyhow::anyhow!("{e}"))?;
let cfg = WasmerConfig::from_file(&wasmer_dir)
.map_err(Error::msg)
.context("Unable to load Wasmer config file")?;
Ok(cfg.registry.get_current_registry())
}
}
}

fn target(&self) -> Result<Target, Error> {
match (self.pip, self.npm, self.yarn) {
(false, false, false) => Err(anyhow::anyhow!(
Expand Down
46 changes: 11 additions & 35 deletions lib/cli/src/commands/config.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use crate::VERSION;
use anyhow::{Context, Result};
use clap::Parser;
use std::env;
use std::path::PathBuf;
use std::str::ParseBoolError;
use wasmer_registry::WasmerConfig;
use wasmer_registry::{wasmer_env::WasmerEnv, WasmerConfig};

#[derive(Debug, Parser)]
/// The options for the `wasmer config` subcommand: `wasmer config get --OPTION` or `wasmer config set [FLAG]`
pub struct Config {
#[clap(flatten)]
env: WasmerEnv,

#[clap(flatten)]
flags: Flags,
/// Subcommand for `wasmer config get | set`
Expand Down Expand Up @@ -168,29 +169,12 @@ impl Config {

fn inner_execute(&self) -> Result<()> {
if let Some(s) = self.set.as_ref() {
return s.execute();
return s.execute(&self.env);
}

let flags = &self.flags;

let key = "WASMER_DIR";
let wasmer_dir = env::var(key)
.ok()
.or_else(|| option_env!("WASMER_INSTALL_PREFIX").map(str::to_string))
.or_else(|| {
// Allowing deprecated function home_dir since it works fine,
// and will never be removed from std.
#[allow(deprecated)]
let dir = std::env::home_dir()?.join(".wasmer").to_str()?.to_string();

Some(dir)
})
.context(format!(
"failed to retrieve the {} environment variables",
key
))?;

let prefix = PathBuf::from(wasmer_dir);
let prefix = self.env.dir();

let prefixdir = prefix.display().to_string();
let bindir = prefix.join("bin").display().to_string();
Expand Down Expand Up @@ -233,9 +217,7 @@ impl Config {
}

if flags.config_path {
let wasmer_dir = WasmerConfig::get_wasmer_dir()
.map_err(|e| anyhow::anyhow!("could not find wasmer dir: {e}"))?;
let path = WasmerConfig::get_file_location(&wasmer_dir);
let path = WasmerConfig::get_file_location(self.env.dir());
println!("{}", path.display());
}

Expand All @@ -244,16 +226,10 @@ impl Config {
}

impl GetOrSet {
fn execute(&self) -> Result<()> {
let wasmer_dir = WasmerConfig::get_wasmer_dir()
.map_err(|e| anyhow::anyhow!("could not find wasmer dir: {e}"))?;
let config_file = WasmerConfig::get_file_location(&wasmer_dir);
let mut config = WasmerConfig::from_file(&wasmer_dir).map_err(|e| {
anyhow::anyhow!(
"could not find config file {e} at {}",
config_file.display()
)
})?;
fn execute(&self, env: &WasmerEnv) -> Result<()> {
let config_file = WasmerConfig::get_file_location(env.dir());
let mut config = env.config()?;

match self {
GetOrSet::Get(g) => match g {
RetrievableConfigField::RegistryUrl => {
Expand Down
18 changes: 12 additions & 6 deletions lib/cli/src/commands/init.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use std::{
collections::HashMap,
path::{Path, PathBuf},
};

use anyhow::Context;
use cargo_metadata::{CargoOpt, MetadataCommand};
use clap::Parser;
use indexmap::IndexMap;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use wasmer_registry::WasmerConfig;
use wasmer_registry::wasmer_env::WasmerEnv;

static NOTE: &str = "# See more keys and definitions at https://docs.wasmer.io/registry/manifest";

Expand All @@ -14,6 +16,9 @@ const NEWLINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
/// CLI args for the `wasmer init` command
#[derive(Debug, Parser)]
pub struct Init {
#[clap(flatten)]
env: WasmerEnv,

/// Initialize wasmer.toml for a library package
#[clap(long, group = "crate-type")]
pub lib: bool,
Expand Down Expand Up @@ -136,6 +141,7 @@ impl Init {
self.template.as_ref(),
self.include.as_slice(),
self.quiet,
self.env.dir(),
)?;

if let Some(parent) = target_file.parent() {
Expand Down Expand Up @@ -347,6 +353,7 @@ fn construct_manifest(
template: Option<&Template>,
include_fs: &[String],
quiet: bool,
wasmer_dir: &Path,
) -> Result<wasmer_toml::Manifest, anyhow::Error> {
if let Some(ct) = cargo_toml.as_ref() {
let msg = format!(
Expand All @@ -365,9 +372,8 @@ fn construct_manifest(
.map(|p| &p.name)
.unwrap_or(fallback_package_name)
});
let wasmer_dir = WasmerConfig::get_wasmer_dir().map_err(|e| anyhow::anyhow!("{e}"))?;
let namespace = namespace.or_else(|| {
wasmer_registry::whoami(&wasmer_dir, None, None)
wasmer_registry::whoami(wasmer_dir, None, None)
.ok()
.map(|o| o.1)
});
Expand Down
Loading

0 comments on commit e96e7b4

Please sign in to comment.