Merge branch 'master' of https://github.com/rustwasm/wasm-pack into issue/189

master
Mackiovello 7 years ago
commit 28d5bb5cab
  1. 4
      .travis.yml
  2. 55
      CHANGELOG.md
  3. 2
      Cargo.lock
  4. 2
      Cargo.toml
  5. 6
      README.md
  6. 5
      src/bindgen.rs
  7. 7
      src/build.rs
  8. 21
      src/command/init.rs
  9. 16
      src/command/mod.rs
  10. 6
      src/command/utils.rs
  11. 13
      src/emoji.rs
  12. 30
      src/error.rs
  13. 7
      src/lib.rs
  14. 2
      src/logger.rs
  15. 23
      src/manifest.rs
  16. 6
      src/npm.rs
  17. 18
      src/progressbar.rs
  18. 3
      src/readme.rs
  19. 88
      tests/manifest/main.rs

@ -7,7 +7,9 @@ matrix:
# tests pass
- rust: nightly
script:
- cargo test --locked
# XXX: `--test-threads 1` is a hack until we have a proper fix for
# synchronizing access to the fixtures.
- cargo test --locked -- --test-threads 1
- rustup component add rustfmt-preview
- cargo fmt --all -- --check
env: RUST_BACKTRACE=1

@ -1,5 +1,60 @@
# Changelog
## ⭐ 0.4.1
- #### 🤕 Fixes
- **fix `files` key value for projects build for `nodejs` target - [ashleygwilliams], [issue/199] [pull/205]**
We became aware that the `files` key in `package.json` did not include the additional `_bg.js` file that
`wasm-bindgen` generates for projects being built for the `nodejs` target. This resulted in the file not
being included in the published package and resulted in a `Module Not Found` error for folks.
This was a group effort from [mciantyre] with [pull/200] and [Brooooooklyn] with [pull/197]. Thank you so
much for your diligence and patience while we sorted through it.
[mciantyre]: https://github.com/mciantyre
[Brooooooklyn]: https://github.com/Brooooooklyn
[issue/199]: https://github.com/rustwasm/wasm-pack/issues/199
[pull/205]: https://github.com/rustwasm/wasm-pack/pull/205
[pull/197]: https://github.com/rustwasm/wasm-pack/pull/197
[pull/200]: https://github.com/rustwasm/wasm-pack/pull/200
- #### 🛠 Maintenance
- **clean up `quicli` remnants - [SoryRawyer], [pull/193]**
In [v0.3.0] we removed the `quicli` dependency, however there were a few remnants
left behind. They are now removed!
[SoryRawyer]: https://github.com/SoryRawyer
[pull/193]: https://github.com/rustwasm/wasm-pack/pull/193
[v0.3.0]: https://github.com/rustwasm/wasm-pack/blob/master/CHANGELOG.md#-030
- #### 📖 Documentation
- **DOCUMENT EVERYTHING!! and deny missing docs for all future development - [fitzgen], [pull/208]**
The `wasm-pack` team has worked hard on tutorial documentation and keeping the codebase as self-explanatory
as possible, but we have been slowly accruing a documentation debt. This amazing PR, landed just moments
before this point release and was just too good not to include. Thank you so much, [fitzgen]!
[fitzgen]: https://github.com/fitzgen
[pull/208]: https://github.com/rustwasm/wasm-pack/pull/208
- **fix README code example - [steveklabnik], [pull/195]**
The code example in our `README.md` was missing a critical `pub`. It's there now!
[pull/195]: https://github.com/rustwasm/wasm-pack/pull/195/files
- **fix README markup - [Hywan], [pull/202]**
There was an errant `` ` `` - it's gone now!
[Hywan]: https://github.com/Hywan
[pull/202]: https://github.com/rustwasm/wasm-pack/pull/202
## 🌟 0.4.0
This release has a ton of awesome things in it, but the best thing is that

2
Cargo.lock generated

@ -669,7 +669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "wasm-pack"
version = "0.4.0"
version = "0.4.1"
dependencies = [
"console 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
"failure 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",

@ -1,7 +1,7 @@
[package]
name = "wasm-pack"
description = "pack up the wasm and publish it to npm!"
version = "0.4.0"
version = "0.4.1"
authors = ["Ashley Williams <ashley666ashley@gmail.com>"]
repository = "https://github.com/ashleygwilliams/wasm-pack.git"
license = "MIT/Apache-2.0"

@ -1,8 +1,8 @@
# 📦✨ wasm-pack
> Your favorite rust -> wasm workflow tool!
[![Build Status](https://travis-ci.org/ashleygwilliams/wasm-pack.svg?branch=master)](https://travis-ci.org/ashleygwilliams/wasm-pack)
[![Build status](https://ci.appveyor.com/api/projects/status/7jjuo5wewu9lyyfi?svg=true)](https://ci.appveyor.com/project/ashleygwilliams/wasm-pack)
[![Build Status](https://travis-ci.org/rustwasm/wasm-pack.svg?branch=master)](https://travis-ci.org/rustwasm/wasm-pack)
[![Build status](https://ci.appveyor.com/api/projects/status/7jjuo5wewu9lyyfi?svg=true)](https://ci.appveyor.com/project/rustwasm/wasm-pack)
This tool seeks to be a one-stop shop for building and working with rust-
generated WebAssembly that you would like to interop with JavaScript, in the
@ -92,7 +92,7 @@ check out our [contribution policy].
6. Run `wasm-pack init`, optionally, pass a path to a dir or a scope (see above for details)
7. This tool generates files in a `pkg` dir
8. To publish to npm, run `wasm-pack publish`. You may need to login to the
registry you want to publish to. You can login using `wasm-pack login`.`
registry you want to publish to. You can login using `wasm-pack login`.
[rust-wasm/36]: https://github.com/rustwasm/team/issues/36
[wasm-bindgen]: https://github.com/alexcrichton/wasm-bindgen

@ -1,9 +1,12 @@
//! Functionality related to installing and running `wasm-bindgen`.
use emoji;
use error::Error;
use progressbar::Step;
use std::process::Command;
use PBAR;
/// Install the `wasm-bindgen` CLI with `cargo install`.
pub fn cargo_install_wasm_bindgen(step: &Step) -> Result<(), Error> {
let msg = format!("{}Installing WASM-bindgen...", emoji::DOWN_ARROW);
PBAR.step(step, &msg);
@ -24,6 +27,8 @@ pub fn cargo_install_wasm_bindgen(step: &Step) -> Result<(), Error> {
}
}
/// Run the `wasm-bindgen` CLI to generate bindings for the current crate's
/// `.wasm`.
pub fn wasm_bindgen_build(
path: &str,
name: &str,

@ -1,9 +1,13 @@
//! Building a Rust crate into a `.wasm` binary.
use emoji;
use error::Error;
use progressbar::Step;
use std::process::Command;
use PBAR;
/// Ensure that `rustup` has the `wasm32-unknown-unknown` target installed for
/// the `nightly` toolchain.
pub fn rustup_add_wasm_target(step: &Step) -> Result<(), Error> {
let msg = format!("{}Adding WASM target...", emoji::TARGET);
PBAR.step(step, &msg);
@ -23,6 +27,7 @@ pub fn rustup_add_wasm_target(step: &Step) -> Result<(), Error> {
}
}
/// Ensure that the `nightly` toolchain is installed in `rustup`.
fn ensure_nightly() -> Result<(), Error> {
let nightly_check = Command::new("rustc").arg("+nightly").arg("-V").output()?;
if !nightly_check.status.success() {
@ -39,6 +44,8 @@ fn ensure_nightly() -> Result<(), Error> {
Ok(())
}
/// Run `cargo build` with the `nightly` toolchain and targetting
/// `wasm32-unknown-unknown`.
pub fn cargo_build_wasm(path: &str, debug: bool, step: &Step) -> Result<(), Error> {
let msg = format!("{}Compiling to WASM...", emoji::CYCLONE);
PBAR.step(step, &msg);

@ -1,3 +1,5 @@
//! Initializing a crate for packing `.wasm`s.
use bindgen;
use build;
use command::utils::set_crate_path;
@ -12,6 +14,7 @@ use std::fs;
use std::time::Instant;
use PBAR;
/// Construct our `pkg` directory in the crate.
pub fn create_pkg_dir(path: &str, step: &Step) -> Result<(), Error> {
let msg = format!("{}Creating a pkg directory...", emoji::FOLDER);
PBAR.step(step, &msg);
@ -20,12 +23,20 @@ pub fn create_pkg_dir(path: &str, step: &Step) -> Result<(), Error> {
Ok(())
}
/// The `InitMode` determines which mode of initialization we are running, and
/// what build and install steps we perform.
pub enum InitMode {
/// Perform all the build and install steps.
Normal,
/// Don't build the crate as a `.wasm` but do install tools and create
/// meta-data.
Nobuild,
/// Don't install tools like `wasm-bindgen`, just use the global
/// environment's existing versions to do builds.
Noinstall,
}
/// Everything required to configure and run the `wasm-pack init` command.
pub struct Init {
crate_path: String,
scope: Option<String>,
@ -38,6 +49,7 @@ pub struct Init {
type InitStep = fn(&mut Init, &Step, &Logger) -> Result<(), Error>;
impl Init {
/// Construct a new `Init` command.
pub fn new(
path: Option<String>,
scope: Option<String>,
@ -92,6 +104,7 @@ impl Init {
}
}
/// Execute this `Init` command.
pub fn process(&mut self, log: &Logger, mode: InitMode) -> Result<(), Error> {
let process_steps = Init::get_process_steps(mode);
@ -161,7 +174,13 @@ impl Init {
fn step_create_json(&mut self, step: &Step, log: &Logger) -> Result<(), Error> {
info!(&log, "Writing a package.json...");
manifest::write_package_json(&self.crate_path, &self.scope, self.disable_dts, step)?;
manifest::write_package_json(
&self.crate_path,
&self.scope,
self.disable_dts,
&self.target,
step,
)?;
#[cfg(not(target_os = "windows"))]
info!(
&log,

@ -1,3 +1,5 @@
//! CLI command structures, parsing, and execution.
pub mod init;
mod login;
mod pack;
@ -13,13 +15,16 @@ use slog::Logger;
use std::result;
use PBAR;
/// The various kinds of commands that `wasm-pack` can execute.
#[derive(Debug, StructOpt)]
pub enum Command {
#[structopt(name = "init")]
/// 🐣 initialize a package.json based on your compiled wasm!
Init {
/// The path to the Rust crate.
path: Option<String>,
/// The npm scope to use in package.json, if any.
#[structopt(long = "scope", short = "s")]
scope: Option<String>,
@ -43,11 +48,17 @@ pub enum Command {
#[structopt(name = "pack")]
/// 🍱 create a tar of your npm package but don't publish!
Pack { path: Option<String> },
Pack {
/// The path to the Rust crate.
path: Option<String>,
},
#[structopt(name = "publish")]
/// 🎆 pack up your npm package and publish!
Publish { path: Option<String> },
Publish {
/// The path to the Rust crate.
path: Option<String>,
},
#[structopt(name = "login", alias = "adduser", alias = "add-user")]
/// 👤 Add a registry user account! (aliases: adduser, add-user)
@ -82,6 +93,7 @@ pub enum Command {
},
}
/// Run a command with the given logger!
pub fn run_wasm_pack(command: Command, log: &Logger) -> result::Result<(), Error> {
// Run the correct command based off input and store the result of it so that we can clear
// the progress bar then return it

@ -1,5 +1,9 @@
//! Utility functions for commands.
use std::path::{Path, PathBuf};
/// If an explicit path is given, then use it, otherwise assume the current
/// directory is the crate path.
pub fn set_crate_path(path: Option<String>) -> String {
let crate_path = match path {
Some(p) => p,
@ -9,6 +13,8 @@ pub fn set_crate_path(path: Option<String>) -> String {
crate_path
}
/// Locates the pkg directory from a specific path
/// Returns None if unable to find the 'pkg' directory
pub fn find_pkg_directory(guess_path: &str) -> Option<PathBuf> {
let path = PathBuf::from(guess_path);
if is_pkg_directory(&path) {

@ -1,3 +1,16 @@
//! Emoji contants used by `wasm-pack`.
//!
//! For the woefully unfamiliar:
//!
//! > Emoji are ideograms and smileys used in electronic messages and web
//! > pages. Emoji exist in various genres, including facial expressions, common
//! > objects, places and types of weather, and animals. They are much like
//! > emoticons, but emoji are actual pictures instead of typographics.
//!
//! -- https://en.wikipedia.org/wiki/Emoji
#![allow(missing_docs)]
use console::Emoji;
pub static TARGET: Emoji = Emoji("🎯 ", "");

@ -4,24 +4,46 @@ use std::borrow::Cow;
use std::io;
use toml;
/// Errors that can potentially occur in `wasm-pack`.
#[derive(Debug, Fail)]
pub enum Error {
/// Maps any underlying I/O errors that are thrown to this variant
#[fail(display = "{}", _0)]
Io(#[cause] io::Error),
/// A JSON serialization or deserialization error.
#[fail(display = "{}", _0)]
SerdeJson(#[cause] serde_json::Error),
/// A TOML serialization or deserialization error.
#[fail(display = "{}", _0)]
SerdeToml(#[cause] toml::de::Error),
/// An error invoking another CLI tool.
#[fail(display = "{}. stderr:\n\n{}", message, stderr)]
Cli { message: String, stderr: String },
Cli {
/// Error message.
message: String,
/// The underlying CLI's `stderr` output.
stderr: String,
},
/// A crate configuration error.
#[fail(display = "{}", message)]
CrateConfig { message: String },
CrateConfig {
/// A message describing the configuration error.
message: String,
},
#[fail(display = "{}", message)]
PkgNotFound { message: String },
/// Error when the 'pkg' directory is not found.
PkgNotFound {
/// Message describing the error.
message: String,
},
}
impl Error {
/// Construct a CLI error.
pub fn cli(message: &str, stderr: Cow<str>) -> Result<(), Self> {
Err(Error::Cli {
message: message.to_string(),
@ -29,12 +51,14 @@ impl Error {
})
}
/// Construct a crate configuration error.
pub fn crate_config(message: &str) -> Result<(), Self> {
Err(Error::CrateConfig {
message: message.to_string(),
})
}
/// Get a string description of this error's type.
pub fn error_type(&self) -> String {
match self {
Error::Io(_) => "There was an I/O error. Details:\n\n",

@ -1,3 +1,7 @@
//! Your favorite rust -> wasm workflow tool!
#![deny(missing_docs)]
extern crate console;
#[macro_use]
extern crate failure;
@ -30,14 +34,17 @@ pub mod readme;
use progressbar::ProgressOutput;
lazy_static! {
/// The global progress bar and user-facing message output.
pub static ref PBAR: ProgressOutput = { ProgressOutput::new() };
}
/// 📦 ✨ pack and publish your wasm!
#[derive(Debug, StructOpt)]
pub struct Cli {
/// The subcommand to run.
#[structopt(subcommand)] // Note that we mark a field as a subcommand
pub cmd: command::Command,
/// Log verbosity is based off the number of v used
#[structopt(long = "verbose", short = "v", parse(from_occurrences))]
pub verbosity: u8,

@ -1,3 +1,5 @@
//! Logging facilities for `wasm-pack`.
use command::Command;
use error::Error;
use slog::{Drain, Level, Logger};

@ -1,3 +1,5 @@
//! Reading and writing Cargo.toml and package.json manifests.
use std::fs::File;
use std::io::prelude::*;
@ -68,16 +70,23 @@ fn read_cargo_toml(path: &str) -> Result<CargoManifest, Error> {
}
impl CargoManifest {
fn into_npm(mut self, scope: &Option<String>, disable_dts: bool) -> NpmPackage {
fn into_npm(mut self, scope: &Option<String>, disable_dts: bool, target: &str) -> NpmPackage {
let filename = self.package.name.replace("-", "_");
let wasm_file = format!("{}_bg.wasm", filename);
let js_file = format!("{}.js", filename);
let dts_file = if disable_dts == true {
None
} else {
Some(format!("{}.d.ts", filename))
};
let js_bg_file = if target == "nodejs" {
Some(format!("{}_bg.js", filename))
} else {
None
};
if let Some(s) = scope {
self.package.name = format!("@{}/{}", s, self.package.name);
}
@ -90,6 +99,13 @@ impl CargoManifest {
None => {}
}
match js_bg_file {
Some(ref js_bg_file) => {
files.push(js_bg_file.to_string());
}
None => {}
}
NpmPackage {
name: self.package.name,
collaborators: self.package.authors,
@ -112,6 +128,7 @@ pub fn write_package_json(
path: &str,
scope: &Option<String>,
disable_dts: bool,
target: &str,
step: &Step,
) -> Result<(), Error> {
let msg = format!("{}Writing a package.json...", emoji::MEMO);
@ -127,7 +144,7 @@ pub fn write_package_json(
let pkg_file_path = format!("{}/pkg/package.json", path);
let mut pkg_file = File::create(pkg_file_path)?;
let crate_data = read_cargo_toml(path)?;
let npm_data = crate_data.into_npm(scope, disable_dts);
let npm_data = crate_data.into_npm(scope, disable_dts, target);
if npm_data.description.is_none() {
PBAR.warn(&warn_fmt("description"));
@ -144,10 +161,12 @@ pub fn write_package_json(
Ok(())
}
/// Get the crate name for the crate at the given path.
pub fn get_crate_name(path: &str) -> Result<String, Error> {
Ok(read_cargo_toml(path)?.package.name)
}
/// Check that the crate the given path is properly configured.
pub fn check_crate_config(path: &str, step: &Step) -> Result<(), Error> {
let msg = format!("{}Checking crate configuration...", emoji::WRENCH);
PBAR.step(&step, &msg);

@ -1,8 +1,12 @@
//! Functionality related to publishing to npm.
use error::Error;
use std::process::{Command, Stdio};
/// The default npm registry used when we aren't working with a custom registry.
pub const DEFAULT_NPM_REGISTRY: &'static str = "https://registry.npmjs.org/";
/// Run the `npm pack` command.
pub fn npm_pack(path: &str) -> Result<(), Error> {
let output = Command::new("npm").current_dir(path).arg("pack").output()?;
if !output.status.success() {
@ -13,6 +17,7 @@ pub fn npm_pack(path: &str) -> Result<(), Error> {
}
}
/// Run the `npm publish` command.
pub fn npm_publish(path: &str) -> Result<(), Error> {
let output = Command::new("npm")
.current_dir(path)
@ -26,6 +31,7 @@ pub fn npm_publish(path: &str) -> Result<(), Error> {
}
}
/// Run the `npm login` command.
pub fn npm_login(
registry: &String,
scope: &Option<String>,

@ -1,15 +1,19 @@
//! Fancy progress bar functionality.
use console::style;
use emoji;
use indicatif::{ProgressBar, ProgressStyle};
use parking_lot::RwLock;
use std::fmt;
/// Synchronized progress bar and status message printing.
pub struct ProgressOutput {
spinner: RwLock<ProgressBar>,
messages: RwLock<String>,
}
impl ProgressOutput {
/// Construct a new `ProgressOutput`.
pub fn new() -> Self {
Self {
spinner: RwLock::new(ProgressBar::new_spinner()),
@ -17,6 +21,8 @@ impl ProgressOutput {
}
}
/// Inform the user that the given `step` is being executed, with details in
/// `message`.
pub fn step(&self, step: &Step, message: &str) {
let msg = format!("{} {}", style(step).bold().dim(), message);
self.message(&msg)
@ -31,6 +37,7 @@ impl ProgressOutput {
message.clear();
}
/// Print the given message.
pub fn message(&self, message: &str) {
self.finish();
@ -45,6 +52,7 @@ impl ProgressOutput {
message.push('\n');
}
/// Add an informational message.
pub fn info(&self, message: &str) {
let info = format!(
"{} {}: {}",
@ -55,6 +63,7 @@ impl ProgressOutput {
self.add_message(&info);
}
/// Add a warning message.
pub fn warn(&self, message: &str) {
let warn = format!(
"{} {}: {}",
@ -65,6 +74,7 @@ impl ProgressOutput {
self.add_message(&warn);
}
/// Add an error message.
pub fn error(&self, message: String) {
let err = format!(
"{} {}: {}",
@ -87,20 +97,28 @@ impl ProgressOutput {
pb
}
/// After having built up a series of messages, print all of them out.
pub fn done(&self) {
self.finish();
}
}
/// For processes that can be broken down into N fractional steps, with messages
/// added for each step along the way like
///
/// > [2/5] Doing the second step out of five.
pub struct Step {
current: usize,
total: usize,
}
impl Step {
/// Construct a `Step` where there are `total` number of steps.
pub fn new(total: usize) -> Step {
Step { current: 1, total }
}
/// Increment the current step.
pub fn inc(&mut self) {
self.current += 1;
}

@ -1,3 +1,5 @@
//! Generating `README` files for the packaged wasm.
use error::Error;
use std::fs;
@ -5,6 +7,7 @@ use emoji;
use progressbar::Step;
use PBAR;
/// Copy the crate's README into the `pkg` directory.
pub fn copy_from_crate(path: &str, step: &Step) -> Result<(), Error> {
let msg = format!("{}Copying over your README...", emoji::DANCERS);
PBAR.step(step, &msg);

@ -6,6 +6,7 @@ extern crate wasm_pack;
mod utils;
use std::collections::HashSet;
use std::fs;
use wasm_pack::manifest;
@ -48,7 +49,7 @@ fn it_creates_a_package_json_default_path() {
let step = wasm_pack::progressbar::Step::new(1);
let path = ".".to_string();
wasm_pack::command::init::create_pkg_dir(&path, &step).unwrap();
assert!(manifest::write_package_json(&path, &None, false, &step).is_ok());
assert!(manifest::write_package_json(&path, &None, false, "", &step).is_ok());
let package_json_path = format!("{}/pkg/package.json", &path);
assert!(fs::metadata(package_json_path).is_ok());
assert!(utils::read_package_json(&path).is_ok());
@ -59,10 +60,16 @@ fn it_creates_a_package_json_default_path() {
pkg.repository.url,
"https://github.com/ashleygwilliams/wasm-pack.git"
);
assert_eq!(pkg.files, ["wasm_pack_bg.wasm", "wasm_pack.d.ts"]);
assert_eq!(pkg.main, "wasm_pack.js");
let types = pkg.types.unwrap_or_default();
assert_eq!(types, "wasm_pack.d.ts");
let actual_files: HashSet<String> = pkg.files.into_iter().collect();
let expected_files: HashSet<String> = ["wasm_pack_bg.wasm", "wasm_pack.d.ts"]
.iter()
.map(|&s| String::from(s))
.collect();
assert_eq!(actual_files, expected_files);
}
#[test]
@ -70,12 +77,20 @@ fn it_creates_a_package_json_provided_path() {
let step = wasm_pack::progressbar::Step::new(1);
let path = "tests/fixtures/js-hello-world".to_string();
wasm_pack::command::init::create_pkg_dir(&path, &step).unwrap();
assert!(manifest::write_package_json(&path, &None, false, &step).is_ok());
assert!(manifest::write_package_json(&path, &None, false, "", &step).is_ok());
let package_json_path = format!("{}/pkg/package.json", &path);
assert!(fs::metadata(package_json_path).is_ok());
assert!(utils::read_package_json(&path).is_ok());
let pkg = utils::read_package_json(&path).unwrap();
assert_eq!(pkg.name, "js-hello-world");
assert_eq!(pkg.main, "js_hello_world.js");
let actual_files: HashSet<String> = pkg.files.into_iter().collect();
let expected_files: HashSet<String> = ["js_hello_world_bg.wasm", "js_hello_world.d.ts"]
.iter()
.map(|&s| String::from(s))
.collect();
assert_eq!(actual_files, expected_files);
}
#[test]
@ -83,12 +98,77 @@ fn it_creates_a_package_json_provided_path_with_scope() {
let step = wasm_pack::progressbar::Step::new(1);
let path = "tests/fixtures/scopes".to_string();
wasm_pack::command::init::create_pkg_dir(&path, &step).unwrap();
assert!(manifest::write_package_json(&path, &Some("test".to_string()), false, &step).is_ok());
assert!(
manifest::write_package_json(&path, &Some("test".to_string()), false, "", &step).is_ok()
);
let package_json_path = format!("{}/pkg/package.json", &path);
assert!(fs::metadata(package_json_path).is_ok());
assert!(utils::read_package_json(&path).is_ok());
let pkg = utils::read_package_json(&path).unwrap();
assert_eq!(pkg.name, "@test/scopes-hello-world");
assert_eq!(pkg.main, "scopes_hello_world.js");
let actual_files: HashSet<String> = pkg.files.into_iter().collect();
let expected_files: HashSet<String> = ["scopes_hello_world_bg.wasm", "scopes_hello_world.d.ts"]
.iter()
.map(|&s| String::from(s))
.collect();
assert_eq!(actual_files, expected_files);
}
#[test]
fn it_creates_a_pkg_json_with_correct_files_on_node() {
let step = wasm_pack::progressbar::Step::new(1);
let path = ".".to_string();
wasm_pack::command::init::create_pkg_dir(&path, &step).unwrap();
assert!(manifest::write_package_json(&path, &None, false, "nodejs", &step).is_ok());
let package_json_path = format!("{}/pkg/package.json", &path);
assert!(fs::metadata(package_json_path).is_ok());
assert!(utils::read_package_json(&path).is_ok());
let pkg = utils::read_package_json(&path).unwrap();
assert_eq!(pkg.name, "wasm-pack");
assert_eq!(pkg.repository.ty, "git");
assert_eq!(
pkg.repository.url,
"https://github.com/ashleygwilliams/wasm-pack.git"
);
assert_eq!(pkg.main, "wasm_pack.js");
let types = pkg.types.unwrap_or_default();
assert_eq!(types, "wasm_pack.d.ts");
let actual_files: HashSet<String> = pkg.files.into_iter().collect();
let expected_files: HashSet<String> =
["wasm_pack_bg.wasm", "wasm_pack_bg.js", "wasm_pack.d.ts"]
.iter()
.map(|&s| String::from(s))
.collect();
assert_eq!(actual_files, expected_files);
}
#[test]
fn it_creates_a_package_json_with_correct_keys_when_types_are_skipped() {
let step = wasm_pack::progressbar::Step::new(1);
let path = ".".to_string();
wasm_pack::command::init::create_pkg_dir(&path, &step).unwrap();
assert!(manifest::write_package_json(&path, &None, true, "", &step).is_ok());
let package_json_path = format!("{}/pkg/package.json", &path);
assert!(fs::metadata(package_json_path).is_ok());
assert!(utils::read_package_json(&path).is_ok());
let pkg = utils::read_package_json(&path).unwrap();
assert_eq!(pkg.name, "wasm-pack");
assert_eq!(pkg.repository.ty, "git");
assert_eq!(
pkg.repository.url,
"https://github.com/ashleygwilliams/wasm-pack.git"
);
assert_eq!(pkg.main, "wasm_pack.js");
let actual_files: HashSet<String> = pkg.files.into_iter().collect();
let expected_files: HashSet<String> = ["wasm_pack_bg.wasm"]
.iter()
.map(|&s| String::from(s))
.collect();
assert_eq!(actual_files, expected_files);
}
#[test]

Loading…
Cancel
Save